views:

337

answers:

3

I have a div, which contains n number of child nodes. I have a for loop:

for (iloop = 0; iloop < summaryDiv.childNodes.length; iloop++) {
    if (summaryDiv.childNodes[iloop].innerHTML.contains('display:block')) {
        flag = false;
    }
}

Here some of the child nodes don't contain the element innerHTML. I need to check if the child node contains innerHTML element, then I need to check for the style (display:block). How can I do this?

A: 

You can check if the element has a property "innerHTML".

<html>
<body>
<div id="div">hello</div>
<script type="text/javascript">

    document.write("div: " + ("innerHTML" in document.getElementById("div")));
    document.write("<br />");
    document.write("div.child: " + ("innerHTML" in document.getElementById("div").firstChild));
</script>
</body>
</html>

produces:

div: true
div.child: false
Sam
+4  A: 

If you want to check the style of something, you do not need innerHTML. Instead, access the display value directly from the style element that is defined by default on DOM elements.

var children = summaryDiv.childNodes; // Avoid excessive scope chain walking (faster!)
for ( var i=0, l=children.length; i<l; i++ ) {
    if ( children[i].style && children[i].style.display == "block" ) {
        flag = false;
    }
}
Justin Johnson
Nimesh
@Nimesh: Check what the value of `children[i]` is (`alert(children[i]);`). It probably isn't a DOM element if the `style` property is undefined.
Steve Harrison
@Nimesh Change `iloop` to `i`. I've made an edit, make sure you have the updated version. @Steve The DOM text node element doesn't define a `style` property, which is why the `children[i].style` check is in place (Nimesh is probably using an older version of the code, I did make an edit).
Justin Johnson
This only looks at immediate children whereas the OP's question with innerHTML looked at all nested chilren.
Sam
A: 

Use the display property directly:

for (var i = 0; i < summaryDiv.childNodes.length; i++) {
    if (summaryDiv.childNodes[i].style && summaryDiv.childNodes[i].style.display == 'block') {
        flag = false;
    }
}
jvenema
getting error heresummaryDiv.childNodes[i][iloop].style is undefined
Nimesh
I'm not sure why you're doing [i][iloop]. Do you really have nested loops? The [i] should be all you need. The check for .style will prevent the style property from ever being used if it's undefined.
jvenema