user433351 user433351 - 4 months ago 9
Javascript Question

How to remove line breaks in between image tags

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.

Answer

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 that match
  // the supplied selector, here we use :not(br)
  // to match 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:

Comments