Search code examples
javascriptdomdotnetnuke

How to remove a Tag using javascript?


I'm in a bit of a pickle. What I'm trying to achieve is to remove a div IF it is empty and then do what I have to afterwards which is the easy bit. The hard part is trying to remove the empty tags. I'm using DNN and it likes to put in empty tags like p and br. I want to be able to remove them before performing my check. Here is my code so far

$(document).ready(function(){
var element = document.getElementsByTagName("p"); //Need to remove all tags. not just P
element.parentNode.removeChild(element); //Doesn't target which child

if( !$.trim( $('#container2Test').html() ).length ) {
    alert("empty");
    $('#container2Test').remove();
    $('#container3Test').css({'width' : '50%', 'background-color' : '#3F0'});
    $('#container3Test').append("This is some content");
}
else{
    alert("not empty");
}
});

The html:

<div id="container1Test" style="width:30%; height:10em; background-color:#000;">
</div>
<div id="container2Test" style="width:50%; height:10em; background-color:#666;">
    <p></p><br /><p></p>
</div>
<div id="container3Test" style="width:20%; height:10em; background-color:#F66;">
</div>

I've tried many options to try and remove the tags but I've had no such luck :( Please help!


Solution

  • As far as your container2test block goes, try using .text() instead of .html(). This will ignore the empty tags that get inserted and focus only on the text content.

    Regarding the piece above it, I'm not quite sure what you're trying to achieve. I don't think it's needed if you implement the change I mentioned earlier.