Remove <h3> by its text content

2.3k views Asked by At

I am trying to remove a 'h3' tag from a header list selecting it by text. For example if I have:

html:

<h3>NO CHANGE</h3>
<h3>h3 to be removed</h3>
<h3>NO CHANGE</h3>
<h3>NO CHANGE</h3>
<h3>NO CHANGE</h3>

jQuery:

var h3_text_remove = $('h3').text();
if (h3_text_remove == 'h3 to be removed'){
    $('h3').remove();
//console.log (h3_text_remove);
}

How can I remove just the header with text 'h3 to be removed'?

fiddle: http://jsfiddle.net/q2nb08t6/7/

5

There are 5 answers

0
Balachandran On BEST ANSWER

You can use contains() selector

$("h3:contains('h3 to be removed')").remove();

Fiddle

0
Rory McCrossan On

You can do this in one line using the :contains() selector:

$('h3:contains("h3 to be removed")').remove();

Or using a variable:

var h3_text_remove = $('#specificH3').text();
$('h3:contains("' + h3_text_remove + '")').remove();

Note that this will remove all h3 elements which contain that text in any way, so both of the following would be removed:

<h3>h3 to be removed</h3>
<h3>foo h3 to be removed bar</h3>

To restrict it to elements containing the whole text only, use filter():

$('h3').filter(function() {
    return $(this).text() == 'h3 to be removed';
}).remove()
0
PeterKA On

Use:

//If text can have leading or trailing spaces
$('h3').filter(function() {
    return $(this).text().trim() == 'h3 to be removed';
}).remove();

//or if the text should match exactly:
$('h3').filter(function() {
    return $(this).text() == 'h3 to be removed';
}).remove();

DEMO 1

$('h3').filter(function() {
    return $(this).text().trim() == 'h3 to be removed';
})
.remove();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h3>NO CHANGE</h3>
<h3>h3 to be removed</h3>
<h3>NO CHANGE</h3>
<h3>NO CHANGE</h3>
<h3>NO CHANGE</h3>
<h3>h3 to be removed </h3>
<h3> h3 to be removed</h3>
<h3>h3 to be removed xx</h3>

DEMO 2

0
Umesh Sehta On

you can use this solution: basic solution to understand easily.

fiddle: http://jsfiddle.net/q2nb08t6/10/

$('h3').each(function(){
var h3_text_remove = $(this).text().trim();

if (h3_text_remove == 'h3 to be removed'){
    $(this).remove();
}
});
0
depperm On

If you just want to remove the tag and not the content

$('h3').each(function(){
    var h3_text_remove = $(this).text().trim();

    if (h3_text_remove == 'h3 to be removed'){
        $(this).unwrap();
    }
});