I'm filtering the entire DOM to replace some strings with other strings.
For this I wrote the following code:
$('body :not(script)').contents().filter(function() {
return this.nodeType === 3;
}).replaceWith(function() {
return this.nodeValue.replace('T 0','T 0');
});
How can I exclude some areas? For example I want the DIV with the class .example
not to be considered.
I tried the following:
$('body :not(script):not(.example)').contents().filter(function() {
return this.nodeType === 3;
}).replaceWith(function() {
return this.nodeValue.replace('T 0','T 0');
});
But this does not seems to work. Why?
CodePudding user response:
Right now, you're telling jQuery to exclude the node .example
, which has children nodes, that WILL be included.
In your :not()
selector add an *
after the class. This will tell jQuery to exclude all nodes underneath the parent node.
In CSS the *
is a universal selector
The CSS universal selector (*) matches elements of any type.
Here's a working version:
(Please note that I changed the
to -
to visually show the change)
$( "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');
});
<!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 >
<p>Remains the same:</p>
<h1>T 0</h1>
</div>
<div>
<p>Changes:</p>
<h1>T 0</h1>
</div>
</body>
</html>