Reputation: 225
I am trying to figure out how to remove line breaks between and after image tags, but leave any others (using jQuery). For example:
<p>
some text
<br>
more text
</p>
<br>
<img src="image.jpg" alt="image">
<br>
<br>
<img src="image2.jpg" alt="image">
<br>
<img src="image3.jpg" alt="image">
<br>
Would become:
<p>
some text
<br>
more text
</p>
<br>
<img src="image.jpg" alt="image">
<img src="image2.jpg" alt="image">
<img src="image3.jpg" alt="image">
Any thoughts would be greatly appreciated.
Upvotes: 0
Views: 412
Reputation: 253396
I'd suggest, for the posted code:
// select all <img> elements:
$('img')
// select all sibling elements of
// the <img> elements that match the
// supplied ('br') selector:
.siblings('br')
// remove those found siblings:
.remove();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>
some text
<br>more text
</p>
<br>
<img src="image.jpg" alt="image">
<br>
<br>
<img src="image2.jpg" alt="image">
<br>
<img src="image3.jpg" alt="image">
<br>
For slightly more complex cases (as well as this one), though, the following may be preferred:
// select all <img> elements:
$('img')
// get all subsequent siblings until an element
// is found which matches the supplied selector
// (':not(br)'), in this case the selector matches
// any element that is not a <br> element:
.nextUntil(':not(br)')
// we remove those elements that are found
// which must be <br> elements, given the
// above selector:
.remove();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
some text
<br>more text
<br>
<img src="image.jpg" alt="image">
<br>
<br>
<img src="image2.jpg" alt="image">
<br>
<img src="image3.jpg" alt="image">
<br>
References:
Upvotes: 4
Reputation: 8795
It remove all <br>
tag between images.
$(document).ready(function(){
$("img").nextUntil('img').remove();
});
<p>
some text
<br>
more text
</p>
<br>
<img src="image.jpg" alt="image">
<br>
<br>
<img src="image2.jpg" alt="image">
<br>
<img src="image3.jpg" alt="image">
Upvotes: 0