Reputation: 51
I would like to remove all the first <br/>
after an <h1>
element.
I have the following HTML:
<div id="myDiv">
<h1>Test</h1>
<br> <!-- <- remove this -->
Lorem ipsum dolor sit amet
<br>
<br>
<h1>Test</h1>
<br> <!-- <- remove this -->
Lorem ipsum dolor sit amet
<br>
<br>
</div>
I wrote this piece of code but it does not remove the first br.
$('#myDiv h1').each(function() {
$(this).closest("br").remove();
});
Upvotes: 0
Views: 639
Reputation: 96
For the future reader that wants a vanilla JavaScript solution. Also, I am not sure if the other posters solutions would remove a <br>
under a different <h1>
if none were found under one.
var eles = document.querySelectorAll('#myDiv h1');
for (var i = 0; i < eles.length; i++) {
var a = eles[i];
while (a.nextElementSibling) {
a = a.nextElementSibling;
if (a.localName) {
if(a.localName == 'br') {
a.parentElement.removeChild(a);
break;
}
else if(a.localName == 'h1')
break;
}
}
}
EDIT: I don't know why I used localName.... tagName probably better.
Upvotes: 1
Reputation: 42054
Using Next Adjacent Selector (“prev + next”) you can write:
$('#myDiv h1 + br').remove();
console.log('BR : ' + $('#myDiv br').length + ' H1 + BR:' + $('#myDiv h1 + br').length);
$('#myDiv h1 + br').remove();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="myDiv">
<h1>Test</h1>
<br> <!-- <- remove this -->
Lorem ipsum dolor sit amet
<br>
<br>
<h1>Test</h1>
<br> <!-- <- remove this -->
Lorem ipsum dolor sit amet
<br>
<br>
</div>
Upvotes: 0
Reputation: 14454
It can be as simple as querying <br/>
tags that come after an <h1/>
tag inside the #myDiv
container:
$('#myDiv h1 + br').remove();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="myDiv">
<h1>Test</h1>
<br> <!-- <- remove this -->
Lorem ipsum dolor sit amet
<br>
<br>
<h1>Test</h1>
<br> <!-- <- remove this -->
Lorem ipsum dolor sit amet
<br>
<br>
</div>
Upvotes: 1
Reputation: 843
$('#myDiv h1').each(function(){
$(this).next('br').remove()
});
Upvotes: 2
Reputation: 20750
You can use jQuery next()
method to do it like following.
$('#myDiv h1').next('br').remove()
Upvotes: 4
Reputation: 27327
You are targeting h3
elements, of which your HTML document has none.
Change your selector to target h1
elements.
$('#myDiv h1')
// ^^
EDIT: Looks like you updated the question to target h1
elements.
Upvotes: 0