The correct way to read-modify-write in an element is to use jQuery "function parameter":
$('div:contains(kamal)').filter(function() { return $(this).children().length === 0;
this avoids calling .text()
twice, and also simplifies the logic of the code.
Please note that you can get unusual results if you have nested div
tags, since the :contains()
pseudo- :contains()
considers all descendants, not just direct children, and makes them top-down, not bottom-up. This is why the above solution includes an initial .filter
call to make sure that only leaf nodes in the DOM tree are considered.
An alternative method is to use .contents
and look directly at the DOM text nodes:
var re = /kamal/gi; $('div').contents().each(function() { if (this.nodeType === 3 && this.nodeValue.match(re)) { this.nodeValue = this.nodeValue.replace(re, ''); } })β
See http://jsfiddle.net/alnitak/eVUd3/
EDIT second example updated to use string.match(regex)
instead of regex.test(string)
.
source share