13

I can get the count of all descendants of an element, but I can't seem to target just the immediate children. Here's what I have at the moment.

var sectionCount = document.getElementById("window").getElementsByTagName("section").length;

I've played with other stuff and different syntax, but I can't seem to get it.

The jQuery equivalent would be:

var sectionCount = $("#window > section").length;

But I need to do this javascript only.

1 Answer 1

19

Use the DOM selector interface (querySelectorAll).

var selectionCount = document.querySelectorAll("#window > section").length;

If you want a backwards compatible solution, loop through childNodes and count element nodes.

var w = document.getElementById('window');
var count = 0; // this will contain the total elements.
for (var i = 0; i < w.childNodes.length; i++) {
    var node = w.childNodes[i];
    if (node.nodeType == Node.ELEMENT_NODE && node.nodeName == "SECTION") {
        count++;
    }
}
Sign up to request clarification or add additional context in comments.

18 Comments

However, this is not compatible in a prehistorical context. IE IEn.
@Caspar - prehistoric lol, it wasn't that long ago. Added a solution for IE.
Sorry for responding so late. I just realize now that it does in fact error in IE. It says "Node is undefined". It shows up on the line where the 'if' statement is. Does something need to be switched around or is there something I should do to define the node.
Replace Node.ELEMENT_NODE with the integer 1.
Log the values of node.nodeType, and node.nodeName and see if they match 1 and "SECTION" respectively.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.