如何在目标页面中删除没有ID's或类名等的HTML元素

How to remove an HTML element in a target page with no ID's or class names, etc.?

本文关键字:元素 HTML ID 目标 删除      更新时间:2023-09-26

我想删除一个具有XPath的元素:

html/body/center/center/table/tbody/tr/td

我想删除<table>及其内容。我找到了一些答案,但他们都需要id, class的名称等。

目标页面就像一个平板

假设这是一个精确精确 XPath,那么您可以使用document.evaluate来删除表,如下所示:

var badTableEval = document.evaluate (
    "//body/center/center/table",
    document.documentElement,
    null,
    XPathResult.FIRST_ORDERED_NODE_TYPE,
    null
);
if (badTableEval  &&  badTableEval.singleNodeValue) {
    var badTable  = badTableEval.singleNodeValue;
    badTable.parentNode.removeChild (badTable);
}



或者使用等效的jQuery。下面是中完整的脚本:

// ==UserScript==
// @name     YOUR_SCRIPT_NAME
// @include  http://YOUR_SERVER.COM/YOUR_PATH/*
// @require  http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js
// @grant    GM_addStyle
// ==/UserScript==
/*- The @grant directive is needed to work around a design change
    introduced in GM 1.0.   It restores the sandbox.
*/
$("body > center:first > center:first > table:first").remove ();


jQuery有一个强大的选择器集合,使用jQuery将在编写脚本的速度、易用性和健壮性方面带来巨大的好处。