1

I'm trying to get the values from a span that doesn't have a class, and I managed to get the value inside one, but I need to get them all at once. This is my code:

<span>one</span>
<span>two</span>  
<span>three</span>
<span>four</span>

var headings = document.evaluate("//span[contains(., 'one')]", document, null, XPathResult.ANY_TYPE, 
null );
var thisHeading = headings.iterateNext();

console.log(thisHeading); // Prints the html element in console
console.log(thisHeading.textContent);

How can it put several values in the document.evaluate(), so I can print all the values?

kjhughes
  • 106,133
  • 27
  • 181
  • 240
delv123
  • 136
  • 13
  • Xpath is one way but if what you want is just get the values and its does not matter to use xpath you can try to get the tag values with getElementsByTagName. All that you need will be; var headings = document.getElementsByTagName("span"); for (index = 0; index < headings.length; ++index) { console.log(headings[index]); } – UserEsp Dec 20 '19 at 15:40
  • The thing is, i have other span's on the code and i need to get que values from those one's only. – delv123 Dec 20 '19 at 15:44

2 Answers2

1

First you need to use or to test for multiple values [contains(.,'one') or contains(.,'two') or ...]

Then you need to use the iterator to loop over the results

var headings = document.evaluate("//span[contains(., 'one') or contains(.,'two')]", document, null, XPathResult.ANY_TYPE,
  null);
var thisHeading;

while (thisHeading = headings.iterateNext()) {
  console.log(thisHeading); // Prints the html element in console
  console.log(thisHeading.textContent);
}
<span>one</span>
<span>two</span>
<span>three</span>
<span>four</span>
Gabriele Petrioli
  • 191,379
  • 34
  • 261
  • 317
1

Note that XPath contains() checks for substrings; for string equality, use = against the string value of the node. See What does contains() do in XPath?

XPath 1.0

Test for alternatives via an or operator in the predicate:

//span[.='one' or .='two' or .='three' or .='four']

XPath 2.0

This can be shortened to:

//span[. = ('one','two','three'.'four')]
kjhughes
  • 106,133
  • 27
  • 181
  • 240