user1823053
user1823053

Reputation: 69

javascript to hide a div if empty

I am looking for javascript (not jquery as client has specified) to hide a div with class=top, if the div has no content. I can do it using jquery like below, but need to use javascript. Any ideas please?

$('div.top:empty').hide();

Upvotes: 0

Views: 396

Answers (5)

Srinivasarao Moka
Srinivasarao Moka

Reputation: 1

Use the following script:

var divContent = $('div .top')[0].innerHTML;

if (divContent === '')
{
    $('div .top').hide();
}

Upvotes: 0

ravisolanki07
ravisolanki07

Reputation: 647

You need to give id to DIV which you want to hide As there are no function in javascript by which you can find div by class. HTML:

<div class="top" id="divId"></div>

Javascript:

if( document.getElementById("divId").innerHTML == "" )
{
   document.getElementById("divId").style.display='none';
}

Upvotes: 0

Hanky Panky
Hanky Panky

Reputation: 46900

(if(document.getElementById("yourDiv").innerHTML=="")
{
  document.getElementById("yourDiv").style.display='none';
}

Upvotes: 1

Sheldon
Sheldon

Reputation: 39

you could use innerHTML property to check if the selected div.top element contains content. something like this.

var topDiv = document.getElementsByClassName('top')[0];
if(topDiv.innerHTML === '') {
    topDiv.style.display = 'none';
}

Upvotes: 1

tymeJV
tymeJV

Reputation: 104775

Something like:

var top = document.getElementsByClassName("top");
for (var i = 0; i < top.length; i++) {
    if (top[i].innerHTML.length == 0)
        top[i].style.display = "none";
}

Upvotes: 1

Related Questions