I would like to set the class of several <tr> elements to reset. This should be done by JavaScript. I know that in general manipulating nodes with JavaScript is easy as this:
function changeclass() {
var trs = document.getElementsByTagName("tr");
for(var i=0; i<trs.length; i++) {
trs[i].className = "reset";
}
};
changeclass();
Now I tried to restrict the selection of <tr> elements to those that entail a <td> that has text equal to reset with the following line doing he selection instead of document.getElementsBy..., which utterly failed:
var trs = document.evaluate( "//td/tr[text()='reset']", document, null, XPathResult.ANY_TYPE, null );
Now I do not know what the problem is, wrong approach? Flaw in my understanding of Javascript? ... ? ... any hints would be appriciated.
Do it the other way around: find the tds, then access the parents:
var tds=table.getElementsByTagName("td");
for (var i=0;i<tds.length;i++) {
if (tds[i].innerHTML.indexOf("reset")>=0){
tds[i].parentNode.className="reset";
}
}
correct expression is
var trs = document.evaluate("//tr[td/text()='rest']", document.body, null, XPathResult.ANY_TYPE, null);
also you can access nodes by trs.iterateNext()
Update
after document changing results will be no longer valid. so you can push them in an array and use it after all iterateNext().
var trsx = document.evaluate("//tr[td/text()='rest']", document.body, null, XPathResult.ANY_TYPE, null);
var trs = [];
if (trsx){
var tr = trsx.iterateNext();
while(tr){
trs.push(tr);
tr = trsx.iterateNext();
}
}
for(var i=0; i<trs.length; i++) {
trs[i].className = "reset";
}
or you can use other XPathResult type.
var trs = document.evaluate("//tr[td/text()='rest']", document.body, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
if (trs){
for(var i=0; i<trs.snapshotLength; i++){
tr = trs.snapshotItem(i);
tr.className = "rest";
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With