Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Javascript to set class of parent node with child's text equal to ...?

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.

like image 769
petermeissner Avatar asked Mar 18 '26 17:03

petermeissner


2 Answers

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";
    }
}
like image 161
Christophe Avatar answered Mar 20 '26 05:03

Christophe


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";                  
    }
}
like image 22
Erfan Avatar answered Mar 20 '26 07:03

Erfan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!