Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript's XPath: How to get the attribute value of an element?

I want to get the value of an attribute of a specific element that has a specific id. For an example I want to get the href of the a tag whose id is next:

<a href="?page=3" id="next">Next</a>

I know I can get it like this:

console.log(document.evaluate('//a[@id="next"]', document, null, XPathResult.ANY_TYPE, null).iterateNext().href);

But the matter is that in my case the name of the attribute may differ and I need a way to specify it via the xpath query. Something like this:

'//a[@id="next"]/@href'
like image 525
Bob Torrent Avatar asked Mar 16 '13 08:03

Bob Torrent


1 Answers

Just try something like this:

document.evaluate('//a[@id="next"]/@href', document, null, XPathResult.ANY_TYPE, null).iterateNext().value;

Depending on the element type you specify in your xpath (element node, text node, attribute), iterateNext() returns different type of object. In this case, specifying @href attribute, it returns a javascript Attr object with the property value containing the value of the attribute. Continuing with your example:

<a href="?page=3" id="next">Next</a>

You can try next examples:

//Returns true
console.log(document.evaluate('//a[@id="next"]/@href', document, 
  null, XPathResult.ANY_TYPE, null).iterateNext() instanceof Attr);

//Returns "?page=3"
console.log(document.evaluate('//a[@id="next"]/@href', document, 
  null, XPathResult.ANY_TYPE, null).iterateNext().value);

//Returns true
console.log(document.evaluate('//a[@id="next"]', document,
  null, XPathResult.ANY_TYPE, null).iterateNext() instanceof Node);

//Returns false
console.log(document.evaluate('//a[@id="next"]', document,
  null, XPathResult.ANY_TYPE, null).iterateNext() instanceof Attr);

//Returns true
console.log(document.evaluate('//a[@id="next"]', document,
  null, XPathResult.ANY_TYPE, null).iterateNext().nodeType === Node.ELEMENT_NODE);

//Returns "Next"
console.log(document.evaluate('//a[@id="next"]', document,
  null, XPathResult.ANY_TYPE, null).iterateNext().textContent);

//Returns true
console.log(document.evaluate('//a[@id="next"]/text()', document,
  null, XPathResult.ANY_TYPE, null).iterateNext() instanceof Node);

//Returns true
console.log(document.evaluate('//a[@id="next"]/text()', 
  document, null, XPathResult.ANY_TYPE, null).iterateNext().nodeType === Node.TEXT_NODE);

//Returns "Next"
console.log(document.evaluate('//a[@id="next"]/text()', document, 
  null, XPathResult.ANY_TYPE, null).iterateNext().nodeValue);
<!DOCTYPE html>
<html>
<body>
<a href="?page=3" id="next">Next</a>
</body>
</html>

Some links that could help you:

  • DOM element's attribute reference

  • Node Types

like image 117
ljmelgui Avatar answered Sep 22 '22 00:09

ljmelgui