Java Script - Get property "innerText" from Table td - javascript

I need to get the text that's written inside a td, but it always gives me an undefined.
This is my try of getting the text:
console.log($('USERvalue'+keykey).prop("innerText"));
console.log($('td[id^="USERvalue"]').prop("innerText"));
Both are the same element. on the first one i target a specific one. In the second line i target several, because i just say the id should start with xy.
But both give me an undefined. If I'm correct that means that it finds the element but cant find any text.
This is the element i try to reach and get the text out of it:
for(let key = 0; key < GlobalVarUS2.length; key++){
let temp = $("<tr><td id='USERvalue"+key+"' value='"+GlobalVarUS2[key]["pk_us_id"]+"'>"+GlobalVarUS2[key]["benutzername"]+"</td><td><input type='checkbox' id='CHBUSER"+key+"' style='size: 30px'></input></td></tr>");
temp.appendTo("#table_user");
}
Ultimately I want to compare it to a string and if it is correct, do something. But first i need the text of the element.
I hope someone can help me :)

You are using $('td[id^="USERvalue"]').text() like a single element. But in real case it is returning multiple elements, So if you want text of all td then you have to process them in loop and you have to contain text in single variable which will be appended each time. for example:
var text="";
$.each($('td[id^="USERvalue"]'),function(k,v){
text += $(v).text();
});
console.log(text);

Related

Scraping data from HTML using JavaScript RegExp [duplicate]

I'm trying to figure out how to, in raw javascript (no jQuery, etc.), find an element with specific text and modify that text.
My first incarnation of the solution... is less than adequate. What I did was basically:
var x = document.body.innerHTML;
x.replace(/regular-expression/,"text");
document.body.innerHTML = x;
Naively I thought I succeeded with flying colors, especially since it was so simple. So then I added an image to my example and thought I could check every 5 seconds (because this string may enter the DOM dynamically)... and the image flickered every 5 seconds.
Oops.
So, there has to be a correct way to do this. A way that specifically singles out a specific DOM element and updates the text portion of that DOM element.
Now, there's always "recursively search through the children till you find the deepest child with the string" approach, which I want to avoid. And even then, I'm skeptical about "changing the innerHTML to something different" being the correct way to update a DOM element.
So, what's the correct way to search through the DOM for a string? And what's the correct way to update a DOM element's text?
Now, there's always "recursively search through the children till you find the deepest child with the string" approach, which I want to avoid.
I want to search for an element in an unordered random list. Now, there's a "go through all the elements till you find what you're looking for approach", which I want to avoid.
Old-timer magno tape, record, listen, meditate.
Btw, see: Find and replace text with JavaScript on James Padolsey's github
(also hig blog articles explaining it)
Edit: Changed querySelectorAll to getElementsByTagName from RobG's suggestion.
You can use the getElementsByTagName function to grab all of the tags on the page. From there, you can check their children and see if they have any Text Nodes as children. If they do, you'd then look at their text and see if it matches what you need. Here is an example that will print out the text of every Text Node in your document with the console object:
var elms = document.getElementsByTagName("*"),
len = elms.length;
for(var ii = 0; ii < len; ii++) {
var myChildred = elms[ii].childNodes;
len2 = myChildred.length;
for (var jj = 0; jj < len2; jj++) {
if(myChildred[jj].nodeType === 3) {
console.log(myChildred[jj].nodeValue);
// example on update a text node's value
myChildred[jj].nodeValue = myChildred[jj].nodeValue.replace(/test/,"123");
}
}
}
To update a DOM element's text, simple update the nodeValue property of the Text Node.
Don't use innerHTML with a regular expression, it will almost certainly fail for non-trivial content. Also, there are still differences in how browsers generate it from the live DOM. Replacing the innerHTML will also remove any event listeners added as element properties (i.e. like element.onclick = fn).
It is best if you can have the string enclosed in an element with an attribute or property you can search on (id, class, etc.) but failing that, a search of text nodes is the best approach.
Edit
Attempting a general purpose text selection function for an HTML document may result in a very complex algorithm since the string could be part of a complex structure, e.g.:
<h1>Some <span class="foo"><em>s</em>pecial</span> heading</h1>
Searching for the string "special heading" is tricky as it is split over 2 elements. Wrapping it another element (say for highlighting) is also not trivial since the resulting DOM structure must be valid. For example, the text matching "some special" in the above could be wrapped in a span but not a div.
Any such function must be accompanied by documentation stating its limitations and most appropriate use.
Forget regular expressions.
Iterate over each text node (and doing it recursively will be the most elegant) and modify the text nodes if the text is found. If just looking for a string, you can use indexOf().
x.replace(/regular-expression/,"text");
will return a value so
var y = x.replace(/regular-expression/,"text");
now you can assign new value.
document.body.innerHTML = y;
Bu you want to think about this, you dont't want to get the whole body just to change one small piece of code, why not get the content of a div or any element and so on
example:
<p id='paragraph'>
... some text here ...
</p>
now you can use javascript
var para = document.getElementById('paragraph').innerHTML;
var newPara = para.replace(/regex/,'new content');
para.innerHTML = newPara;
This should be the simplest way.

Insert a cell with javascript and then insert checkboxes into it?

I want to create a table with javascript, and in some of the cells, put in radiobuttons and checkboxes with javascript.
I found this code:
function insRow() {
var x = document.getElementById('myTable').insertRow(0);
var y = x.insertCell(0);
y.setAttribute('id', "NewDiv");
}
(the last line (setAttribute) is a line that I added. I thought that I could give the new table cell an ID, and then use document.GetElementByID with that ID in various subroutines. That does not work. Now maybe making a global variable to store a copy of 'y' in would work - I could use it in the routines. But shouldn't the above code also work?
The document.getElementById method (lowercase "g" and "d") will only work once the element is added to the DOM.
Ultimately, if possible, do your manipulations from the y variable, before it's appended, but it will be accessible by ID just like any other element.

get the next row in a table-javascript

how wud u get the next row in the following example? (i am trying to print the next three row/column values of the rowId provided)
function printRowData(rowId)
{
var row=document.getElementById(rowId);
for(i=0; i<3 ; i++)
{
var column=row.getElementsByTagName("td");
alert(column[0].innerText);
//now i want to move to the next row...something like row=row.next()?????
}
}
If you just want the next row, and not subsequent rows, you can do this:
var next = row.parentNode.rows[ row.rowIndex + 1 ];
So your code could look like this:
function printRowData(rowId) {
var row=document.getElementById(rowId);
var idx = row.rowIndex;
for(i=0; i<4 ; i++) {
if( row ) {
alert(row.cells[0].innerText);
var row = row.parentNode.rows[ ++idx ];
}
}
}
From the current row, it gets the .parentNode, then from that, it accesses the rows collection, and increments the .rowIndex property of the original row to select the next.
This takes care of white space issues.
Notice also that instead of getElementsByTagName, I replaced it with row.cells, which is a collection of the cells in the row.
EDIT: Forgot to include the rows property after parentNode. It was included in the description though. Fixed.
To get around the problems with whitespace you can now use
row = row.nextElementSibling
Just make sure to check for null when you get to the end of the table, or if you have a thead, tbody or tfoot it will be at the end of that particular node.
If you're supporting older browsers you may want to use a shim.
Try using the nextSibling property:
row = row.nextSibling
But note that whitespace in your source HTML may turn into text nodes among the rows. You may have to call nextSibling more than once to skip the text nodes.
Have you considered using jQuery? With jQuery, you don't have to worry about the text nodes:
row = $("#" + rowId);
...
row = row.next();
row = row.nextSibling. You might need to do that in a while loop as you may come across whitespace nodes, so you should check to see if the next node has the correct tagName.
If you can use jQuery, then it's becoming really easy.
row.next();
Use document.getElementById(rowId).nextSibling

Finding the DOM element with specific text and modify it

I'm trying to figure out how to, in raw javascript (no jQuery, etc.), find an element with specific text and modify that text.
My first incarnation of the solution... is less than adequate. What I did was basically:
var x = document.body.innerHTML;
x.replace(/regular-expression/,"text");
document.body.innerHTML = x;
Naively I thought I succeeded with flying colors, especially since it was so simple. So then I added an image to my example and thought I could check every 5 seconds (because this string may enter the DOM dynamically)... and the image flickered every 5 seconds.
Oops.
So, there has to be a correct way to do this. A way that specifically singles out a specific DOM element and updates the text portion of that DOM element.
Now, there's always "recursively search through the children till you find the deepest child with the string" approach, which I want to avoid. And even then, I'm skeptical about "changing the innerHTML to something different" being the correct way to update a DOM element.
So, what's the correct way to search through the DOM for a string? And what's the correct way to update a DOM element's text?
Now, there's always "recursively search through the children till you find the deepest child with the string" approach, which I want to avoid.
I want to search for an element in an unordered random list. Now, there's a "go through all the elements till you find what you're looking for approach", which I want to avoid.
Old-timer magno tape, record, listen, meditate.
Btw, see: Find and replace text with JavaScript on James Padolsey's github
(also hig blog articles explaining it)
Edit: Changed querySelectorAll to getElementsByTagName from RobG's suggestion.
You can use the getElementsByTagName function to grab all of the tags on the page. From there, you can check their children and see if they have any Text Nodes as children. If they do, you'd then look at their text and see if it matches what you need. Here is an example that will print out the text of every Text Node in your document with the console object:
var elms = document.getElementsByTagName("*"),
len = elms.length;
for(var ii = 0; ii < len; ii++) {
var myChildred = elms[ii].childNodes;
len2 = myChildred.length;
for (var jj = 0; jj < len2; jj++) {
if(myChildred[jj].nodeType === 3) {
console.log(myChildred[jj].nodeValue);
// example on update a text node's value
myChildred[jj].nodeValue = myChildred[jj].nodeValue.replace(/test/,"123");
}
}
}
To update a DOM element's text, simple update the nodeValue property of the Text Node.
Don't use innerHTML with a regular expression, it will almost certainly fail for non-trivial content. Also, there are still differences in how browsers generate it from the live DOM. Replacing the innerHTML will also remove any event listeners added as element properties (i.e. like element.onclick = fn).
It is best if you can have the string enclosed in an element with an attribute or property you can search on (id, class, etc.) but failing that, a search of text nodes is the best approach.
Edit
Attempting a general purpose text selection function for an HTML document may result in a very complex algorithm since the string could be part of a complex structure, e.g.:
<h1>Some <span class="foo"><em>s</em>pecial</span> heading</h1>
Searching for the string "special heading" is tricky as it is split over 2 elements. Wrapping it another element (say for highlighting) is also not trivial since the resulting DOM structure must be valid. For example, the text matching "some special" in the above could be wrapped in a span but not a div.
Any such function must be accompanied by documentation stating its limitations and most appropriate use.
Forget regular expressions.
Iterate over each text node (and doing it recursively will be the most elegant) and modify the text nodes if the text is found. If just looking for a string, you can use indexOf().
x.replace(/regular-expression/,"text");
will return a value so
var y = x.replace(/regular-expression/,"text");
now you can assign new value.
document.body.innerHTML = y;
Bu you want to think about this, you dont't want to get the whole body just to change one small piece of code, why not get the content of a div or any element and so on
example:
<p id='paragraph'>
... some text here ...
</p>
now you can use javascript
var para = document.getElementById('paragraph').innerHTML;
var newPara = para.replace(/regex/,'new content');
para.innerHTML = newPara;
This should be the simplest way.

Change the content inside the <td> with the help of id of <tr>

How can I get the second child node of a tr, which has 3 td in it?
I have a code
rows=document.getElementById('mytr');
rows.firstChild.innerHTML='ddsds';
rows.lastChild.innerHTML='dd';
Now I would like to change the content in the middile also. how can I do that?
rows.secondChild.innerHTML='ddsds';
will not work.
Although I'd recommend using something like jQuery for this kind of manipulation, this is what you want:
var rows = document.getElementById('mytr');
var cells = table.getElementsByTagName('td');
cells[0].innerHTML = 'ddsds';
cells[1].innerHTML = 'ddsds';
cells[2].innerHTML = 'dd';
Access the childNodes or cells as array
rows.childNodes[1].innerHTML would do the second cell, as would
rows.cells[1].innerHTML
you can also use nextSibling,
rows.firstChild.nextSibling.innerHTML='ddsds';
and be careful while accessing child, these can return a text node if there are some white spaces. always try to validate if the child is not a text node using
rows.firstChild.nodeType == 1 // this will check if the node is not a text node
You can use .childNodes to find childnode by it's index.
rows.childNodes[1].innerHTML = 'foo'; // set foo to second child
if (rows.childNodes.length > 0)
rows.childNodes[1].innerHTML = "ddsds";

Categories