'div:contains not a valid selector
I'm following this example and typed $( "div:contains('John')" ).css( "text-decoration", "underline" ); , but got an exception:
VM23376:1 Uncaught DOMException: Failed to execute '$' on 'CommandLineAPI': 'div:contains('John')' is not a valid selector.
Solution 1:[1]
You can use JS vanilla to do this :
function contains(selector, text) {
var elements = document.querySelectorAll(selector);
return Array.from(elements).filter(function(element) {
return RegExp(text).test(element.textContent);
});
}
// Run Code
let found = contains('span', 'Find');
// You can also search with regex
found = contains('span', 'Find\\s*[A-Za-z]+');
for (let i = 0; i < found.length; i++) {
let elem = found[i];
elem.style.backgroundColor = 'red';
}
<p>Some text where you have span tag that said <span>Find Me</span></p>
Solution 2:[2]
I guess it was a copy-paste issue.
OP typed 'div:contains('John')' instead of "div:contains('John')".
Properly copy-pasted code works without any problem.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>contains demo</title>
<script src="https://code.jquery.com/jquery-3.5.0.js"></script>
</head>
<body>
<div>John Resig</div>
<div>George Martin</div>
<div>Malcom John Sinclair</div>
<div>J. Ohn</div>
<script>
$( "div:contains('John')" ).css( "text-decoration", "underline" );
</script>
</body>
</html>
Solution 3:[3]
function '$' is unknow. You probably trying to execute this code in place where jQuery library wasn't loaded.
$( "div:contains('John')" ).css( "text-decoration", "underline" );
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
John
</div>
Solution 4:[4]
it works for me as expected without an error as you can see the screenshot.
you can run this link also click on this link to see example
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>contains demo</title>
<script src="https://code.jquery.com/jquery-3.5.0.js">.
</script>
</head>
<body>
<div>John Resig</div>
<div>George Martin</div>
<div>Malcom John Sinclair</div>
<div>J. Ohn</div>
<script>
$("div:contains('John')").css("text-decoration",
"underline");</script>
</body>
</html>
Solution 5:[5]
Workaround: Manually filter elements by text instead:
$('div').filter(function(element){
return $(element).text().includes('John')
}).css('text-decoration', 'underline' )
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Antoine Guerra |
| Solution 2 | yurin |
| Solution 3 | Dawid Wekwejt |
| Solution 4 | Muneer Khan |
| Solution 5 |

