Can't get textContent from [Object Text]?

I want the script to find where it says “any word” in xml (inside the tag, of course) and stop there. below is a penalty.

var xmlDoc = loadXMLDoc("nhl.xml"); var x = xmlDoc.getElementsByTagName("tagname"); for (var i=0;i<=x.length;i++){ if (x[i].textContent = "anyword") { var variable = x[i].textContent; } } 

However, I want to take it one step further and be able to set the “variable” to the next node after it finds “any word”. so I tried something like this and it came back with the very last item in the collection, not the next one.

 var xmlDoc = loadXMLDoc("nhl.xml"); var x = xmlDoc.getElementsByTagName("tagname"); for (var i=0;i<=x.length;i++){ if (x[i].textContent = "anyword") { var variable = x[i+1].textContent; } } 

so I edited the last line again and made it

 var variable = x[i].nextSibling.textContent; 

it returned null. tearing out my hair. if this helps answer anyone, if I just put it x[i].nextSibling , it returns [Object Text]

any help?

+4
source share
3 answers

By x[i].textContent = "anyword" do you mean x[i].textContent == "anyword" ?

+4
source

This is a common problem for people. Modern browsers (basically everything except IE) will add text nodes between elements. These text nodes contain only spaces and are not very useful. Use this function to find the next node.

 function nextSibling(node) { do { node = node.nextSibling; } while (node && node.nodeType != 1) ; return node } 

It is very well explained here: JavaScript XML Parsing

+3
source
 var xmlDoc = loadXMLDoc("nhl.xml"); var x = xmlDoc.getElementsByTagName("tagname"); for (var i=0;i<=x.length;i++){ if (x[i].textContent = "anyword") { var variable = x[i+1].textContent; } } 

I did not look in detail, but it seems strange to me:

 for (var i=0;i<=x.length;i++) 

You tried

 for (var i=0;i<x.length;i++) 
0
source

Source: https://habr.com/ru/post/1336229/


All Articles