0

I am having trouble coming up with a jQuery script that will all content of a div if there are no unordered list items present. So if there are unordered list items inside of the div then the div will be displayed, otherwise it will be hidden.

here is the basic html I have to test this:

<html>
<title>Experiment Fix Div Hidding</title
<head>

<link rel="stylesheet" type="text/css" href="css/css.css" media="all"/>
<script src="js/jquery-1.7.1.min.js"></script>
<script type="text/javascript" src="js/scripts.js"></script>

</head>

<body>

<table>

<tr>
<td>
<div id="contenFirst">Sample Content. Not display if not bullets points exists
<ul>
<li><a href="#">Hello world</a></li>
<li><a href="#">Hello world2</a></li></ul></div>
</td>
</tr>

</table>

</body>
</html>

Here is the script I have come up with so far, but it doesn't seem to do the job:

$(document).ready(function(){

// hiding a div based on it not having any content (unordered list items)
if($("#contentFirst").html().length == 0){
$("#contentFirst").hide();
} 
});

I am going in the right way with the jquery script, haven't done much with jquery before.

Any suggestions will be greatly appreciated.

Dev P
  • 1,157
  • 5
  • 32
  • 54

3 Answers3

3

Try this:

$(document).ready(function() {
    $('#contentFirst').hide();
    $('#contentFirst').has('ul').show();
});
Andrew Cooper
  • 32,176
  • 5
  • 81
  • 116
2

Firstly, it looks like you may have a typo :)

<div id="contenFirst">Sample Content. Not display if not bullets points exists
<ul>

Your contentFirst is missing a "t".

Secondly, you want to count the <li> list items, but the immediate child of contentFirst is the <ul> which will never go away, so contentFirst will always have content.

You could do this:

if($("#contentFirst").find("li").length === 0){
    $("#contentFirst").hide();
} 

find() will return all of the <li> items even if they are not immediate children!

sth
  • 222,467
  • 53
  • 283
  • 367
jowo
  • 1,981
  • 17
  • 20
1

This will return true if your div doesn't have any unordered lists:

if($("#contentFirst ul").length == 0){

Also if you want to simply hide your div if it doesn't have a ul you can do the following:

$("#contentFirst:not(:has(ul))").hide();
xbrady
  • 1,683
  • 14
  • 23