SVG and XPATH

by mklemma

HTML

<button id="button1" >/html/body/div/p</button>
<button id="button2" >/html/body/svg/text</button>
<button id="button3" >/html/body/*[name()='svg']/*[name()='text']</button>

<div>
<p>hello world1</p>
</div>
<svg xmlns="http://www.w3.org/2000/svg">
      <text x="0" y="20">
         hello world2
      </text>
      <text x="0" y="60">
         hello world3
      </text>
</svg>

JavaScript

document.getElementById("button1").onclick=button1Func; 
document.getElementById("button2").onclick=button2Func; 
document.getElementById("button3").onclick=button3Func; 
  
function alertTextContent(xpath){
	var result = document.evaluate(xpath, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null);
  if(result.singleNodeValue == null){
		alert("xpath failed!")
  }else{
  	const text = result.singleNodeValue.textContent;
		alert(text)  
  }
}
function button1Func(){
	alertTextContent("/html/body/div/p");
}
function button2Func(){
	alertTextContent("/html/body/svg/text");
}
function button3Func(){
	alertTextContent("/html/body/*[name()='svg']/*[name()='text']");
}