0

My HTML contains divs some of it dont have any content and some contains only white space. I want to remove those divs with regular expression.

I written code but it seems not right. fiddle

var patt= new RegExp("<div></div>");
document.querySelector('.wrapper').innerHTML.replace(patt,'') 
Jitender
  • 7,593
  • 30
  • 104
  • 210
  • 1
    [*Do not do this*](http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454). <:o – RobG Aug 17 '15 at 04:51

3 Answers3

3

Use dom manipulation instead of regex to modify html content

var els = document.querySelectorAll('.wrapper div'),
  el;
for (var i = 0; i < els.length; i++) {
  el = els[i];
  if ((el.textContent || el.innerText).trim() == '') {
    el.parentNode.removeChild(el)
  }
}
div:not(.wrapper) {
  background-color: #ff0000;
  padding: 10px;
  margin: 5px
}
<div class="wrapper">
  <div>text</div>
  <div></div>
  <div>text</div>
  <div>text</div>
  <div><span></span>
  </div>
  <div>
  </div>
</div>
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
1
  1. String.replace() does not change the original string.
  2. You should use the "g" flag to remove all empty divs and not only the first occurrence.
var patt = new RegExp("<div>\\s*</div>", "g");
var wrapperDiv = document.querySelector('.wrapper');
wrapperDiv.innerHTML = wrapperDiv.innerHTML.replace(patt, '')
Lars Gendner
  • 1,816
  • 2
  • 14
  • 24
0

Add \\s*, inbetween those tags.. \\s* matches zero or more white-spaces(vertical aswell as horizontal white-space).

var patt= new RegExp("<div>\\s*</div>", "g");

var s = '<div class="wrapper">\n    <div>text</div>\n    <div></div>\n    <div>text</div>\n    <div>text</div>\n    <div></div>\n</div>'
alert(s.replace(/<div>\s*<\/div>/g, ''))

or

var s = '<div class="wrapper">\n    <div>text</div>\n    <div></div>\n    <div>text</div>\n    <div>text</div>\n    <div></div>\n</div>'
alert(s.replace(/\s*<div>\s*<\/div>/g, ''))
Avinash Raj
  • 172,303
  • 28
  • 230
  • 274