0

How would I use jQuery or plain JavaScript to remove the spaces before and after the <nospc/> tag in the code below? (I realize I could simply remove the spaces manually, but sometimes it's convenient to have spaces and line breaks in the HTML that are not rendered.)

<div>
    <img src="" /><nospc/>
    <img src="" />
</div>

In a perfect world <nospc/> would remove all white space before and after the itself, and <nospc> ... </nospc> would remove all white space between the tag pair.

StormDog
  • 91
  • 6

1 Answers1

0

Try utilizing .contents() , .each() Node.nextSibling , Node.previousSibling , Node.textContent , String.prototype.replace() with RegExp /\s+/

$("div").contents().each(function(i, el) {
  if (el.nodeName === "#text" && el.nextSibling 
       && el.nextSibling.nodeName === "NOSPC" 
     || el.nodeName === "#text" && el.previousSibling 
       && el.previousSibling.nodeName === "NOSPC" 
     || el.nodeName === "NOSPC") {
         el.textContent = el.textContent.replace(/\s+/g, "")
  }
});

console.log($("div").contents())
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<div>
    <img src="" /> <nospc> </nospc> 
    <img src="" />
</div>
guest271314
  • 1
  • 15
  • 104
  • 177