Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

remove any word using remove() in jQuery

Tags:

jquery

I want to make a function that remove any specific word in the content

I got this code

jQuery

<script>
$(document).ready(function(){
    $('#cl').click(function(){
        $('div').remove(':contains("kamal")');
    });
    
    
})
</script>

HTML

<div>asdjh alsdhj kamal ljkahsdhasd lakshd kamal</div>
<div ><a href="#" id="cl">click</a></div>
<div>asdjh alsdhj  ljkahsdhasd lakshd </div>

but its remove whole div contains kamal I want to remove only this word from my content not the whole div you can also see online demo of my code here

like image 297
Kamal Avatar asked May 15 '12 07:05

Kamal


1 Answers

The correct way to do a read-modify-write on an element is to use jQuery's "function parameter" methods:

$('div:contains(kamal)').filter(function() {
    return $(this).children().length === 0;  // exclude divs with children
}).text(function(index, text) {
    return text.replace(/kamal/g, '');
});

this avoids calling .text() twice, and also simplifies the code logic.

Note that you may get unusual results if you have nested div tags, since the :contains() pseudo selector considers all descendants, not just direct children, and does it top-down rather than bottom-up. This is why the above solution includes the initial .filter call, to ensure that only leaf nodes in the DOM tree are considered.

An alternative method is to use .contents and look directly at 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 https://jsfiddle.net/alnitak/eVUd3/

EDIT second example updated to use string.match(regex) instead of regex.test(string).

like image 96
Alnitak Avatar answered Sep 22 '22 02:09

Alnitak