this is the code i am using to get all text content from webpage. yet its not working and I do not know what i am doing wrong.
<tr style="color:#000000" class="odd">
<td style="padding:5px 5px 5px 10px" align="center"><input type="checkbox" name="cards[]" id="card_278002" value="278002"></td>
<td align="center">411756</td>
<td align="center">Sherrie</td>
<td align="center">89852</td>
</tr>
and thats my Js code :
function get42() {
return document.querySelectorAll('tr>td').textContent;
}
console.log(page.evaluate(get42));
Output : null .. what am I doing wrong ?
You can't use document.querySelectorAll like that. It returns a NodeList. You have to take the textContent from each Node yourself.
Longer way:
function get42() {
var tds = document.querySelectorAll('td'),
result = [];
for (var i = 0; i < tds.length; i++) {
result.push(tds[i].textContent);
}
return result;
}
Or Shorter:
function get42() {
var tds = document.querySelectorAll('td');
return Array.prototype.map.call(tds, function(t) { return t.textContent; });
}
js fiddle
Related
How can i do this code work with multiple classes?
$("td.field_358").each(function() {
var td = document.getElementsByClassName('field_358');
for (i = 0; i < td.length; i++) {
if (td[i].innerHTML.indexOf('Yes') !== -1) {
td[i].style.backgroundColor = '#f7fef7';
} else if (td[i].innerHTML.indexOf('No') !== -1) {
td[i].style.backgroundColor = '#fbe8ea';
}
}
})
Actually i'm repeating the code for diferents classes, just replacing the class... field_358, field_123...etc.
Its possible to do something more handy like:
$("td.field_358", "td.field_359", "td.field_360").each(function() {
var td = document.getElementsByClassName('field_358', 'field_359', 'field_360');
});
I'm a JS Noob...
You may put all the css-classes you're interested in in an array and iterate over that. For each iteration you execute the code you've already got:
['field_358', 'field_359', 'field_360'].forEach(function (cssClass) {
var td = document.getElementsByClassName(cssClass);
for (i = 0; i < td.length; i++) {
if (td[i].innerHTML.indexOf('Yes') !== -1) {
td[i].style.backgroundColor = '#f7fef7';
} else if (td[i].innerHTML.indexOf('No') !== -1) {
td[i].style.backgroundColor = '#fbe8ea';
}
}
});
A working example may be found at https://jsfiddle.net/9sba06r4/3
Side note: You don't need jQuery for this task, just a more-or-less up-to-date browser.
Sources: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach, https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach
Here's a reusable function that allows you to pass an array of numbers representing the ids you wish to target, and also allows you to pass in strings representing the colors you wish to use for highlighting.
You simply define your arguments to the function and call it.
const ids = [1, 2, 3, 4];
const yesColor = '#37fef7';
const noColor = '#fbe8ea';
highlightTds(ids, yesColor, noColor);
function highlightTds(ids, yesColor, noColor) {
ids.map(id => {
const tds = document.querySelectorAll(`.field_${id}`);
for (const key of Object.keys(tds)) {
if (tds[key].innerHTML.indexOf('Yes')) {
tds[key].style.backgroundColor = yesColor;
} else if (tds[key].innerHTML.indexOf('No')) {
tds[key].style.backgroundColor = noColor;
}
}
});
}
<table>
<tr>
<td class="field_1">Yes</td>
</tr>
<tr>
<td class="field_2">No</td>
</tr>
<tr>
<td class="field_3">Yes</td>
</tr>
<tr>
<td class="field_4">No</td>
</tr>
<tr>
<td class="field_2">Yes</td>
</tr>
<tr>
<td class="field_1">No</td>
</tr>
</table>
I have HTML table with three rows and three cells for each row. Each cell has class name. I want to get the class name of each cell and write it to array.
HTML table:
<table>
<tr>
<td class="O-marker"></td>
<td class="O-marker"></td>
<td class="X-marker"></td>
</tr>
<tr>
<td class="X-marker"></td>
<td class="O-marker"></td>
<td class="X-marker"></td>
</tr>
<tr>
<td class="X-marker"></td>
<td class="O-marker"></td>
<td class="O-marker"></td>
</tr>
</table>
When the getBoard function is called, then get all the class names of cells and write it to board array.
function getBoard() {
var board = [];
return board;
}
I want to use jQuery and .each() method to get the class name and push the first character into the array board. Example. By the first character I mean (X or O).
Using vanilla JS:
function getBoard() {
var board = [];
var tds = document.getElementsByTagName('td');
for (var i = 0; i < tds.length; i += 1) {
board.push(tds[i].className[0]);
}
return board;
}
Or in jQuery:
function getBoard() {
var board = [];
$('td').each(function(){
board.push(this.className[0]);
});
return board;
}
Using jQuery:
function getBoard() {
var board = [];
$('.table td').each(function (index) {
board.push($(this).attr('class')[0]);
});
return board;
}
console.log(getBoard());
You can treat the string as an array (sort of?) and get the first character with [0].
I'm a beginner with code,
I'm trying to run on this table and get the text from each .winner class and push it to an Array, so instead of getting:
["aa","aa","dd"]
I'm getting
["aaaadd","aaaadd","aaaadd"]
$(document).ready(function(){
var arr = [];
var winner = $('.winner').text() ;
for ( i = 0; i < $('table').length ; i++ ) {
arr.push(winner);
}
console.log(arr);
});
HTML:
<table>
<tr>
<td>#</td>
<td class="winner">aa</td>
<td>bb</td>
<td>cc</td>
<td>dd</td>
</tr>
</table>
<table>
<tr>
<td>#</td>
<td class="winner">aa</td>
<td>bb</td>
<td>cc</td>
<td>dd</td>
</tr>
</table>
<table>
<tr>
<td>#</td>
<td class="winner">dd</td>
<td>cc</td>
<td>bb</td>
<td>aa</td>
</tr>
</table>
I guess something is wrong with my for loop
var arr = [];
$('table .winner').each(function () {
arr.push($(this).text());
})
Example
or version without class .winner
$('table').each(function () {
arr.push($(this).find('tr').eq(0).find('td').eq(1).text());
});
Example
$('table .winner') - returns 3 td's with class .winner
$(this).text() - get text from current element.
In your example $('.winner').text() returns text "aaaadd", then you get $('table').length (will be 3) and three times push the same text to arr
The sentence
var winner = $('.winner')
will give you an array of objects, so you need to loop each of them and call text() method for each one.
With this:
var winner = $('.winner').text();
You are getting a combined texts from all the td elements marked as winner (see docs here).
Then, for each table, to push this value to the array:
for ( i = 0; i < $('table').length ; i++ ) {
arr.push(winner);
}
This is actually not necessary.
What you want is probably:
var winners = $('.winner');
for (var i = 0; i < winners.length(); ++i) {
arr.push(winners.eq(i).text());
}
i have this code:
<table>
<tbody>
<tr>
<td align="left">X</td>
<td>X1</td>
</tr>
<tr>
<td width="150" align="left">Y</td>
<td>Y1</td>
</tr>
<tr>
<td align="left">Status: </td>
<td colspan="4">
<select name="status" size="1">
<option selected="selected" value="2">one</option>
<option value="1">two</option>
</select>
</td>
</tr>
<tr>
<td width="150" align="left">Z</td>
<td>Z1</td>
</tr>
</tbody>
</table>
and want to remove with Javascript this line:
<tr>
<td align="left">Status: </td>
<td colspan="4">
<select name="status" size="1">
<option selected="selected" value="2">one</option>
<option value="1">two</option>
</select>
</td>
</tr>
the problem is that i don't have any id's or classes for identification.
is there a way to remove the row by searching "Status: " or name="status" with javascript for Firefox only (using it for Greasemonkey)?
i can't use jQuery and i can't edit the code to set any id's
best regards
bernte
If you can afford not being compatible with IE7, You can do that :
​var elements = document.querySelectorAll('td[align="left"]');
for (var i=0; i<elements.length; i++) {
var text = elements[i].textContent || elements[i].innerText;
if (text.trim()=='Status:') {
elements[i].parentNode.parentNode.removeChild(elements[i].parentNode);
}
}
Demonstration
To be compatible with IE7, you'd probably have to iterate on all rows and cells, which wouldn't really be slower but would be less clear.
Note that I used trim which doesn't exist on IE8. To make it work on this browser if needed, you might add this usual fix (from MDN) :
if(!String.prototype.trim) {
String.prototype.trim = function () {
return this.replace(/^\s+|\s+$/g,'');
};
}
function removeRowByCellValue(table,cellValue) {
var cells = table.getElementsByTagName("TD");
for(var x = 0; x < cells.length; x++) {
// check if cell has a childNode, prevent errors
if(!cells[x].firstChild) {
continue;
}
if(cells[x].firstChild.nodeValue == cellValue) {
var row = cells[x].parentNode;
row.parentNode.removeChild(row);
break;
}
}
}
First get a reference to your table, since you do not have an ID you can use getElementsByTagName.. (here i'm assuming that it is the first table in your document)
var myTable = document.getElementsByTagName("table")[0];
Then you can invoke the function with the following parameters
removeRowByCellValue(myTable,"Status: ");
var xpathResult = document.evaluate("//td[starts-with(.,'Status:')]", document.body, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null);
var element = xpathResult.singleNodeValue.parentNode;
while (element.firstChild)
element.removeChild(element.firstChild);
Jsbin http://jsbin.com/urehuw/1/edit
And if you'd like to be compatible with older IE:
function closest(el, tag) {
if (!el || !tag) {
return false;
}
else {
return el.parentNode.tagName.toLowerCase() == tag ? el.parentNode : closest(el.parentNode, tag);
}
}
// gets all 'select' elements
var sel = document.getElementsByTagName('select');
// iterates through the found 'select' elements
for (var i=0, len = sel.length; i<len; i++) {
// if the 'select' has the name of 'status'
if (sel[i].name == 'status') {
// uses the closest() function to find the ancestor 'tr' element
var row = closest(sel[i], 'tr');
// access the 'tr' element's parent to remove the 'tr' child
row.parentNode.removeChild(row);
}
}
JS Fiddle demo.
simply use this
var gettag =document.getElementsByTagName("tr")[3] ; // the third tag of tr
document.removeChild(gettag);
I have the following div that contains the table and its data queried from database
<div id="content">
<table>
<tbody>
<tr>
<th class="header" colspan="2">Food items include:</th>
</tr>
<tr>
<td id="15" class="fruits">Papaya+salt</td>
<td><p>This includes papaya and salt</p></td>
</tr>
<tr>
<td class="meat">Baked chicken</td>
<td><p>This includes a chicken thide and kethup</p></td>
</tr>
<tr>
<td id="1" class="Juices">Strawberry Sting</td>
<td><p>Sugar, color and water</p></td>
</tr>
<table>
</div>
That table is defined in a page.aspx
and here is my code used to sort that table data alphabetically
OldFunc = window.onload;
window.onload = OnLoad;
function OnLoad(){
try{
var pathName = window.location.pathname.toLowerCase();
if( pathName=="/Resources/Glossary.aspx") {
sort_it();
}
OldFunc();
}
catch(e) {
}
}
function TermDefinition(def_term,def_desc)
{
this.def_term=def_term;
this.def_desc=def_desc;
}
function sort_it()
{
var gloss_list=document.getElementsByTagName('td');
var desc_list=document.getElementsByTagName('td p');
var gloss_defs=[];
var list_length=gloss_list.length;
for(var i=0;i<list_length;i++)
{
gloss_defs[i]=new TermDefinition(gloss_list[i].firstChild.nodeValue,desc_list[i].firstChild.nodeValue);
}
gloss_defs.sort(function(a, b){
var termA=a.def_term.toLocaleUpperCase();
var termB=b.def_term.toLocaleUpperCase();
if (termA < termB)
return -1;
if (termA > termB)
return 1;
return 0;
})
for(var i=0;i<gloss_defs.length;i++)
{
gloss_list[i].firstChild.nodeValue=gloss_defs[i].def_term;
desc_list[i].firstChild.nodeValue=gloss_defs[i].def_desc;
}
}
Please lookat the the two getElementsByTagName, I think I am misuse its content since nothing is done on the output.
Invalid:
desc_list=document.getElementsByTagName('td p');
You can't pass a css selector to that function, only a tag name like div\ span input etc'.
You might want to use:
desc_list = $('td p');
Since you tagged the question with jQuery, or document.querySelectorAll for vanilla js:
desc_list = document.querySelectorAll('td p');