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?

2
  • 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]); } Commented Dec 20, 2019 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. Commented Dec 20, 2019 at 15:44

2 Answers 2

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>

Sign up to request clarification or add additional context in comments.

Comments

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')]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.