Reputation: 3470
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/
Upvotes: 1
Views: 2440
Reputation: 24638
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>
Upvotes: 4
Reputation: 337560
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()
Upvotes: 1
Reputation: 10746
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();
}
});
Upvotes: 1
Reputation: 10683
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();
}
});
Upvotes: 1
Reputation: 9637
You can use contains() selector
$("h3:contains('h3 to be removed')").remove();
Upvotes: 4