javascript - How do I use Greasemonkey to hide an XPath element? - Stack Overflow

I have an XPath htmlbodydiv[1]divdivcenter[1]table and I would like to make it so it is no longe

I have an XPath /html/body/div[1]/div/div/center[1]/table and I would like to make it so it is no longer visible.

I saw I could use document.evaluate() but I am not sure how to hide it.

I have an XPath /html/body/div[1]/div/div/center[1]/table and I would like to make it so it is no longer visible.

I saw I could use document.evaluate() but I am not sure how to hide it.

Share Improve this question edited Nov 12, 2014 at 9:00 Brock Adams 93.7k23 gold badges241 silver badges305 bronze badges asked Nov 12, 2014 at 7:35 BijanBijan 8,73221 gold badges102 silver badges162 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 6

If you insist on using XPath, for a single node, use FIRST_ORDERED_NODE_TYPE like so:

var targEval = document.evaluate (
    "/html/body/div[1]/div/div/center[1]/table",
    document.documentElement,
    null,
    XPathResult.FIRST_ORDERED_NODE_TYPE,
    null
);
if (targEval  &&  targEval.singleNodeValue) {
    var targNode  = targEval.singleNodeValue;

    // Payload code starts here.
    targNode.style.display = "none";
}



But, XPath selectors are very brittle in userscripts. You're better off using a CSS selector in most cases.
Since the HTML wasn't provided, here is the CSS-selector method shown with a translation of that XPath into a CSS selector:

var targNode = document.querySelector ("body > div:nth-of-type(1) > div > div > center:nth-of-type(1) > table");
if (targNode) {
    targNode.style.display = "none";
}



Of course, it's even simpler with jQuery:

$("body > div:first > div > div > center:first > table").hide ();

or possibly:

$("body > div:first > div > div > center:first > table").first ().hide ();



If the node is added via AJAX, use a technique such as in this answer.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745115149a4612083.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信