Skip to content Skip to sidebar Skip to footer

Selecting
  • Child Node But Not Grandchildren With Vanilla JavaScript
  • I have some lists set up like the following:

    Solution 1:

    To get direct children of the ul#menu use children HTMLCollection:

    var X = document.getElementById("menu").children;
    

    Alternatively, you could select the same collection of li elements with querySelectorAll method using direct children selector:

    var X = document.querySelectorAll("#menu > li");
    

    Solution 2:

    Why not using document.querySelectorAll for this. It is wide supported: http://caniuse.com/#feat=queryselector

    And it is easy to query like in css style. Hope it help. Here is the documentation of how to use it: https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll

    Also can be interested in this for selecting single item: https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector

    var childNodes = document.querySelectorAll("#menu > li");
    

    Solution 3:

    var X = document.getElementById("menu");
    var Y = X.getElementsByTagName("li");
    
    
    
    for (var i = 0; i < Y.length; i++) {
     if(Y[i].parentNode.getAttribute('id')=='menu') {
    
    
       var Z = Y[i].getElementsByTagName('a');
       console.log(Z[0].innerHTML);
    
       }
    
    
    
    
    }
    

    Demo: http://jsfiddle.net/txmvshpa/3/


    Post a Comment for "Selecting
  • Child Node But Not Grandchildren With Vanilla JavaScript"