I want to remove the elements where there is no content. For example this is my HTML markup:
I have the html markup in a jquery variable say var myhtml and I am not sure of any specific tags in it.
<h1>
<u>
<strong></strong>
</u>
<u>
<strong>Read This Report Now
<strong></strong> ??
</strong>
</u>
</h1>
As we can see that above markup
<u>
<strong></strong>
</u>
is empty and hence this should be removed from the markup. Say I have the above markup in a variable myhtml
. How can I do this?
I am not sure if the element will be either
"<u>" or "<em>" or "<i>" or "<div>" or "<span>"
.. It can be anything.
You can search all elements and remove which is empty.
$('*').each(function(){ // For each element
if( $(this).text().trim() === '' )
$(this).remove(); // if it is empty, it removes it
});
See how works!: http://jsfiddle.net/qtvjj3oL/
UPDATED:
You also can do it without jQuery
:
var elements = document.getElementsByTagName("*");
for (var i = 0; i < elements.length; i++) {
if( elements[i].textContent.trim() === '' )
elements[i].parentNode.removeChild(elements[i]);
}
See jsfiddle: http://jsfiddle.net/qtvjj3oL/1/
UPDATED 2:
According to your comment, you have the html in a variable, you can do it:
// the html variable is the string wich contains the html
// We make a fake html
var newHtml = document.createElement('html');
var frag = document.createDocumentFragment();
newHtml.innerHTML = html;
frag.appendChild(newHtml);
var elements = newHtml.getElementsByTagName("*");
// Remove the emptys elements
for (var i = 0; i < elements.length; i++) {
if( elements[i].textContent.trim() === '' )
elements[i].parentNode.removeChild(elements[i]);
}
html = newHtml.innerHTML; // now reset html variable
It works: http://jsfiddle.net/qtvjj3oL/6/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With