简体   繁体   中英

Why does the content return the same object on JavaScript?

In Javascript code below, which is running on the Chrome console (the web page is just a random search result on Google):

var result = document.getElementsByClassName('g')

var xpath = "//h3[contains(text(),'wrong')]";

for (let i = 0; i < result.length; i++) {
    var r = document.evaluate(xpath, result[i], null, XPathResult.FIRST_ORDERED_NODE_TYPE, null)
    console.log(i);
    console.log(r.singleNodeValue);
    result[i].style.display = 'none';
}

I want to search for a keyword on each relevant search result item, and if there is, hide the item from the result. However, the output above seems to repeat the search result that has the keyword, even though in my test sample the keyword is included only on one item.

0
<h3 class=​"LC30li DRV0Md">​Why is this code not working</h3>​
1
<h3 class=​"LC30li DRV0Md">Why is this code not working</h3>​

..... (up to the last search item)

So the loop is running but it seems that r.singleNodeValue always returns the same object.

I wonder why it doesn't show a result from each item.

From Document.evaluate MDN docs:

document.evaluate(".//h2", document.body, null, XPathResult.ANY_TYPE, null);

Notice in the above document.body has been used as the context instead of document so the XPath starts from the body element. (In this example, the "." is important to indicate that the querying should start from the context node, document.body . If the "." was left out (leaving //h2 ) the query would start from the root node (html) which would be more wasteful.)

So I think you just need to add a '.' at the start of your xpath. Here you always get the first element matching in the whole document, ignoring the context element you provided

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM