Join CSnippTM today and be a part of 5,000+ developers like you. for FREE !!!
 

Count the elements inside a dom node   1989

Description   

Counts how many children elements are contained in an element node.


Short url  
Snippet
window.onload = init;

function init() {
    get('go').onclick = function() {
        var result =countTags(document.body);
        
        console.log(result);
    };
}

/*
 * Counts how many children elements are
 *  contained in an element node.
 * Parameter
 *  Object - A Dom node.
 * Return
 *  Integer - The count of contained
 *  elements.
*/
function countTags(n) {
    var numTags = 0;
    
    // Check if the passed node is an
    //  element node.
    if (n.nodeType === 1) {
        numTags++;
    } 
    // Take all the children ...
    var children = n.childNodes;
    // ... loop over the children.
    for (var i = 0; i < children.length; i++) {
        // Recursive call.
        numTags += countTags(children[i]);
    }
    // Return the count.
    return numTags;
}

function get(id) {
    return document.getElementById(id);
}


Comments



    Register/Login to Chat and take part in the discussion


    mizech-profile-picture

    mizech  (3)

    Click to view more