我正在过滤整个 DOM 以用其他字符串替换某些字符串。
为此我编写了以下代码:
$('body :not(script)').contents().filter(function() {
return this.nodeType === 3;
}).replaceWith(function() {
return this.nodeValue.replace('T 0','T 0');
});
Run Code Online (Sandbox Code Playgroud)
如何排除某些区域?例如,我希望.example
不考虑具有类的 DIV。
我尝试了以下方法:
$('body :not(script):not(.example)').contents().filter(function() {
return this.nodeType === 3;
}).replaceWith(function() {
return this.nodeValue.replace('T 0','T 0');
});
Run Code Online (Sandbox Code Playgroud)
为什么这似乎不起作用?
现在,您告诉 jQuery 排除.example
将包含的具有子节点的节点。
在您的:not()
选择器中添加一个*
类后。这将告诉 jQuery 排除父节点下的所有节点。
在 CSS 中*
是通用选择器
CSS 通用选择器 (*) 匹配任何类型的元素。
这是一个工作版本:(请注意,我将 更改
为-
以便直观地显示更改)
$( "input:not(:checked) + span" ).css( "background-color", "yellow" );
$( "input").attr( "disabled", "disabled" );
$('body :not(script):not(div.example *)').contents().filter(function() {
return this.nodeType === 3;
}).replaceWith(function() {
return this.nodeValue.replace('T 0','T--0');
});
Run Code Online (Sandbox Code Playgroud)
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>not demo</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<div class="example">
<p>Remains the same:</p>
<h1>T 0</h1>
</div>
<div>
<p>Changes:</p>
<h1>T 0</h1>
</div>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)