🖥️프론트엔드/HTML | CSS | JAVASCRIPT

자바스크립트 - XPATH 문법으로 DOM ELEMENT 가져오기

Janger 2023. 11. 12. 21:37
728x90

 

XPATH 문법으로 단일 요소 가져오기
function getElementByXpath(path){
	return document.evaluate(path, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
}

console.log( getElementByXpath("//html[1]/body[1]/div[1]"));

 

XPATH 문법으로 다중 요소 가져오기
function getElementsByXPath(xpath, parent)
{
    let results = [];
    let query = document.evaluate(xpath, parent || document,
        null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
    for (let i = 0, length = query.snapshotLength; i < length; ++i) {
        results.push(query.snapshotItem(i));
    }
    return results;
}

let items = getElementsByXPath("//*"); // return all elements on the page

 

 

출처: 

https://sensitivity-dev.tistory.com/21

 

Javascript XPath를 이용해서 Dom Element 가져오기

Javascript XPath를 이용해서 Dom Element 가져오기 function getElementByXpath(path) { return document.evaluate(path, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;} console.log( getElementByXpath("//html[1]/body[1]/div[1

sensitivity-dev.tistory.com

 

https://stackoverflow.com/questions/36303869/how-to-use-document-evaluate-and-xpath-to-get-a-list-of-elements

 

How to use document.evaluate() and XPath to get a list of elements?

I'm using the document.evaluate() JavaScript method to get an element pointed to by an XPath expression: var element = document.evaluate( path, document, null, XPathResult.

stackoverflow.com

 

728x90