Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I have little big problem. I try almost everything and I am not able to select an element from table if I know some commented text. I think that this is not possible. For example
<table id='table1'>
<tr>
<td>
Some text
</td>
<td>
<!-- someid="id301" -->
</td>
</tr>
<tr>
<td>
Some next text
</td>
<td>
<!-- someid="id303" -->
</td>
</tr>
<table>
OK. So I only know for example this value someid="301" or someid="302". And I need to get parent element for example to change color of this by jquery. I really tested everything and I am not able to get tr element. Thank you for your help.
You can filter out the content of each TDs but honestly i don't see any purpose for that:
var someValue = 'someid="id303"';
$('table').find('td').contents().filter(function(){
return this.nodeType === 8 && this.nodeValue.indexOf(someValue) != -1;
}).closest('tr').css('background-color', 'red');
-jsFiddle-
If you need that string to setup something, then generally it is not a good practice to put that string in comment.
I would suggest you to put that someid as a data attribute in td element
<td data-someid="id301">...</td>
then you can access it by $td.attr("data-someid") or even use it in jQuery selector
$('td[data-someid="id301"]').css('background-color', 'green');
You can use jQuery Comments() Plug-in or
<input type="hidden" id="id301">
Try this:
<script>
var tableId = 'table1';
var table = document.getElementById(tableId);
var trs = table.getElementsByTagName('tr');
// Pattern for searching for the string like someid="id[somenumbersinarow]"
var pattern = /someid=\"id[0-9]+\"/
// Pattern for searching for numeric value
var numericPattern = /[0-9]+/
var innerHTML, tr;
for (var i = 0, amountOfTrs = trs.length; i < amountOfTrs; i++){
tr = trs[i];
innerHTML = tr.innerHTML;
/* Searching for the comment with "someid" string, turning it into string
(it will be the only string because there will be a single element in the array),
then again search for numbers, convert to string and try to parse it) */
console.log(parseInt(innerHTML.match(pattern).toString().match(numericPattern)));
}
</script>
This script properly works if there's only one comment per the TR element
pattern is a regular expression object. It can be used with modifiers such as g (search for ALL the matches in the text), for instance: /[0-9]+/g. In this case you'll get an array which may have a length greater than 1.
In the example I provided the modifier isn't used, so toString() method will return a string in this case. If you go further and try to get a number by another pattern, then you can use parseInt to extract number (id)
Be aware that if the match() method doesn't find anything it returns null, so before invoking function like in my example, you should either strongly know that this comment exists or perform some additional check.
Related
This question already has answers here:
Javascript .querySelector find <div> by innerTEXT
(14 answers)
Closed 3 years ago.
I have a string which contains HTML TD tags. I want to construct a regex to fetch that TD which has innerHTML "Number"
Example:
Following are the whole string
var rows = `<td width="69" style="white-space:normal">Name</td>
<td width="70" style="white-space:normal;border-left:none">Number</td>
<td width="64" style="white-space:normal;border-left:none">Type</td>`;
Regex should be:
If I put "Number" in regex, second TD tag should fetched. If I put "Name", first TD tag should fetched.
Thank you,
https://regex101.com/r/gsXlab/1
/<td[^>]+?>Number<\/td>/g
Try this. But next time please try first and put your question with some code you tried.
Using DOM instead of RegEx
Javascript .querySelector find by innerTEXT
Examples were not hard to find
Note you can create the fragment outside the function to reuse it
var cells = `<td width="69" style="white-space:normal">Name</td>
<td width="70" style="white-space:normal;border-left:none">Number</td>
<td width="64" style="white-space:normal;border-left:none">Type</td>`;
function contains(selector, text) {
var fragment = document.createElement("TR");
fragment.innerHTML=cells;
var elements = fragment.querySelectorAll(selector);
return Array.prototype.filter.call(elements, function(element){
return RegExp(text).test(element.textContent);
});
}
console.log("Name",contains('td', 'Name')[0]); // rmeove [0] to get more than one
console.log("Number",contains('td', 'Number')[0]);
console.log("Type",contains('td', 'Type')[0]);
This is the basic format of the code the table is contained within a div named
<div class="leftCol">
.....
<tr id="my_cd">
<td><span class="agt_span">My Code</span></td>
</tr>
.....
</div>
I need to be able to get whatever text is contained within the span class, in this case I need to pull the text "My Code" and then add that into an array. Adding the text into an array is not the issue that's easy but I can't figure out how to pull the text. No matter what I try I can't get anything but an 'undefined' value.
How do I get the Inner HTML text value for a span by class name?
First Question solved thanks!!
Second question expand on first:
<div class="leftCol">
.....
<tr id="my_cd">
<td><span class="agt_span">My Code</span></td>
<td>
<div>
<select name="agt_drp" id="agt_drp" class="agt_drp">...</select>
</div>
</td>
</tr>
</div>
Let's say I have the select id "agt_drp" and I want to get the span class text. Is there any way to do that?
Jquery:
var test = $("span.agt_span").text();
alert(test):
Javascript:
http://www.w3schools.com/jsref/met_document_getelementsbyclassname.asp
in vanilla javascript, you can use getElementsByClassName():
var htmlString = document.getElementsByClassName('agt_span')[0].innerHTML;
https://jsfiddle.net/ky38esoo/
Notice the index behind the method.
JQuery:
$('span.agt_span').text();
Pure JavaScript (you need to specify the position of your class element: [0] to get the first one):
document.getElementsByClassName('agt_span')[0].innerHTML;
If you have multiples elements with this class, you can loop on it:
var elts = document.getElementsByClassName('agt_span');
for (var i = 0; i < elts.length; ++i) {
alert(elts[i].innerHTML);
}
Though getElementsByClassName seems to be supported by all major browser, that is now argument to use it. To keep your code compatible and usefull, better use the W3C Standard DOM Level 3 Core. The Document IDL does not describe such a method there!
So please use
var table = document.getElementById("my_cd"); /* id is unique by definition! */
var spans = table.getElementsByTagName("span");
var txt;
for(i in spans) {
if(spans[i].getAttribute("class").contains("agt_span")){
txt = spans[i].firstChild; /* a span should have only one child node, that contains the text */
}
}
return txt;
This method isn't perfect, as you actually need to split the spans[i].getAttribute("class").split(" ") on space chars and check if this array contains "agt_span".
By the way: innerHTML is no DOM Attribute too. But you can implement anything in a compatible and flexible way using W3C DOM and you will be sure to write effective and compatible code.
If the js programmers had used the W3C Documents and if there weren't no Internet Explorer to break all those ECMAScript and W3C rules, there would never have been that many incompatibilities between all those browser versions.
This question already has answers here:
Get text inside HTML comment tag?
(2 answers)
Closed 8 years ago.
I need to select the table cell, that has a comment, which contains the word "Baseline EUI" and in that cell I need to add unit name next to the value ("59") like km or miles etc. How do I select the cell, provided the only thing that uniquely identifies that table cell is the keyword inside the comment i.e. "Baseline EUI" ? Please help me how I can select this table cell using jQuery? (I need to add unit like Km or Miles right after the number 59 in the table cell)
<tr>
<td width="165" class="ms-formlabel" noWrap="nowrap" vAlign="top">
<H3 class=ms-standardheader><A name=SPBookmark_BaselineEUI></A>Baseline EUI</H3>
</td>
<td width="450" class="ms-formbody" id="SPFieldNumber" vAlign="top">
<!-- FieldName="Baseline EUI" FieldInternalName="BaselineEUI" FieldType="SPFieldNumber" -->
59
</td>
</tr>
<tr>
There are many rows/cells like the above...
</tr>
I haven't test this code. But it should work in your case.
please verify and make necessary changes.
$.each($("yourtable tr"),function(i,val){
var check=false;
//check if Baseline EUI is contained inside tr
if($(val).html().indexOf('Baseline EUI'))
{
var x=$(val).find('td')[1];
var p=$(x).html()+' km';//set your suffix
$(x).html(p)
}
});
or use this as a selector of the right tr:
$(".ms-formtable tr").filter(function (i, v) { if ($(this).html().indexOf('Zugehoerigkeit') > 0) { return this; } })
First you select the tr tag then loop throw the contents of each tr tag searching for the content which contains the word you are searching for .
$( "tr" ).each(function() {
});
For adding the unit you want, you would do the same but when you find that cell, you will the index method of jquery to know where the number is and then use jquery substring method to split the value of that cell in two parts adding your unit to the first part and then make the value of that cell = the first part (after adding your unit) + the second part (using jquery substring method).
Please, let me know in the comments if you need detailed code .
I was trying to replace multiline string with another multiline string using javascript.
How do I do that?
For example the pseudo code for this could be as shown below, where the string to search and set are runtime variables/arguments (not hardcoded as shown below), so we cannot create fixed regular expressions.
Any idea?
The string to search for looks like,
<tr>
<td colspan="3" class="footer"> </td>
</tr></tbody></table>
and let the string to replace be,
<tr>
<td colspan="3" class="footer">New Arrivals!!!</td>
</tr>
<tr>
<td colspan="3" class="footer"> </td>
</tr></tbody></table>
Pseudo code,
var regExp = new RegExp(strMultiLineTextToSearch.trim(), "gm");
var matches = htmlContent.match(regExp);
alert(matches.length);
if(matches.length > 0){
var newHtml= htmlContent.replace(regExp , strMultiLineTextToSet );
}
Using Firefox 22.0
also, the strings are prased from webpage using some string foo and innerHTML.
EEEK! Don't use HTML manipulation to add content to a table. That would be like adding a small detail to a big painting by having a painter describe the picture to you, then paint a new picture based on that description, except you change that little detail in the description.
Not just it's incredibly slow, but the painter is likely to not use the very same words you used when telling him to draw the picture the first time. You will be confused if he says "young woman" instead of "lady". You wanted the lady to hold something, but there's only a young woman. Instead, you should tell the painter to give the lady that something.
The same applies here: are you sure you use the exact same amount of whitespace in the string you're searching as is in the table? If there isn't, the string won't be found. Even if there is, how can you be sure the browser doesn't rearrange the attributes within a tag (IE loves to sort them alphabetically)? Add whitespace after the arguments? Some browser extension may add its own attributes or classes...
Instead, use DOM manipulation. That's the picture. HTML is its description.
If you add an ID to that row, it will be easy to find from javascript. Then create the new element and place it before that row.
var lastRow = document.getElementById("last-row")
var td = document.createElement("td")
td.className = "footer"
td.colspan = 3
var text = document.createTextNode("New arrivals!!!")
td.appendChild(text)
lastRow.parent.insertBefore(lastRow, td)
If the table is easy to find, you can access its last row via that table:
var table = document.getElementById("my-table")
var lastRow = table.rows[table.rows.length - 1]
...
It seems you are using the table to layout your page. This is not a clean approach (the page is not semantically a table, lots of unneccessary elements; please note the distinction between <table> and display:table). Adding an empty spacing cell is almost certainly wrong. Use CSS margin-bottom or padding-bottom instead (unless you're making an HTML email - in which case, use CSS anyways, then convert to a mail-safe form using some freeware web service that exists for that purpose). CSS is not hard. Not using it is much harder.
You can't have Strings spanning across multiple lines. If you want a String that contains newline characters you'll have to use escape sequences: \n. Also pay attention not to use double quotes in a string that is itself enclosed in double quotes - you need to escape those, too.
var foo = "I am a string that contains a \" double quote"
or
var foo = 'I am a string that contains a " double quote'
are legal while
var foo = "I am a string that contains a " double quote"
is not
The problem I see here is that you're using double quotes where they are not allowed and lack of \n in the end of each line in your strings:
var strMultiLineTextToSearch =
"<tr>
<td colspan="3" class="footer"> </td>
</tr></tbody></table>";
should be
var strMultiLineTextToSearch =
"<tr>
<td colspan='3' class='footer'> </td>
</tr></tbody></table>";
I am learning Jquery and Javascript from web examples. I have a good working knowledge but some code still trips me up. The following code is used for a shopping cart to hide the check out button and replace with a div displaying a message about minimum cart requirements. There is a part of the code throwing me off though.
function getCollectionCount() {
var totalCollectionCount = 0;
var collection = $('td[alt*="Collection"]');
for (var i = 0; i < collection.length; i++) {
var curVal = $(collection[i]).find("select").val();
if (curVal != undefined){
totalCollectionCount += parseInt(curVal);
}
}
What does this part mean?
var collection = $('td[alt*="Collection"]');
td[alt*="Collection"] selects all <td> elements whose alt attribute contains Collection, such as:
<td alt="Collection"></td>
<td alt="CollectionFoo"></td>
<td alt="BarCollection12324343"></td>
but not
<td></td>
<td alt=""></td>
<td alt="Foo"></td>
Side note: this is a pretty basic question that could easily be answered by read the jQuery selectors API documentation:
element selector
attribute-contains selector
Please do try to research before you ask!
This is a jQuery attribute selector clause. It's selecting any td element which has an atrtibute named alt whose string contains the value Collection.
Contains Selector: http://api.jquery.com/attribute-contains-selector/
jQuery has a number of useful attribute selectors. Here is the main reference page for them. Very much worth the read if you're just getting started with jQuery
http://api.jquery.com/category/selectors/attribute-selectors/
That code returns every td element whose "alt" attribute contains "Collection".
http://api.jquery.com/attribute-contains-selector/
jQuery is full of these funky shortcuts that take forever to learn, so I always keep a copy of jQuery in action on my desk at all times :)
This code can be rewritten more simply and briefly like this:
function getCollectionCount() {
var totalCollectionCount = 0;
$('td[alt*="Collection"] select').each(function() {
var val = this.value || "0";
totalCollectionCount += parseInt(val, 10);
});
return(totalCollectionCount);
}
And, this is how it works:
Initialize totalCollectionCount to 0
Find all td elements that have the string "Collection" in the alt attribute and then find select elements within that td
Iterate over all elements found that match the above condition
Initialize a local variable with either the value of the select object or "0" if there is no value or it's empty
Turn that value into a number (must pass the radix to parseInt so it won't guess) and add it to the sub-total so far.
return the total we found.