Numb3rs
Numb3rs

Reputation: 5

How can I hide a DOM element that contains no text?

I am wondering how to hide a DOM element in JavaScript if it doesn't contain any text, for example:

<ul>
  <li>Text</li>
  <li>Text</li>
  <li>Text</li>
  <li>Text</li>
  <li>Text</li>
  <li>Text</li>
  <li></li> <!-- Element to hide -->
</ul>

I've currently written:

var point = document.getElementsByTagName("li");
for(var i = 0; i < point.length; i++){
   if(point[i].text==""){
      point[i].style.display = "none";
   }
}

Thank you!

Upvotes: 0

Views: 75

Answers (2)

Michelangelo
Michelangelo

Reputation: 5958

Why don't you use jQuery for this, it will smooth out the browser differences:

$('li').each(function (){
    if($(this).html()==="") {
        $(this).css({"display":"none"});   
    }
});

Upvotes: 1

Sushanth --
Sushanth --

Reputation: 55750

Use innerHTML property and remove the empty spaces first before making a check againts it.

 if(!/[\S]/.test(point[i].innerHTML)) { 
    point[i].style.display = "none";
 }

Upvotes: 0

Related Questions