Search code examples
javascripthtmlprototypejs

how to get all outer(parent) divs id values from wrapper div using prototype?


I want to get only first outer all divs id value from below HTML structure.

I want to output like p1,test,contents which is outer divs ids value("p1,test,contents") in "padder" div not all divs id value . i tried below code but it returns all div ids value but i want to only outer divs id and its value like p1,test,contents(this is outer divs id and its value which i want) in below html structure.

$('padder').select('div').each(function(el){
  alert($(el).id);
}); 

<div id="padder">
  <div id="p1">
    <div id="s1">
    </div><!-- Ends s1 div-->
  </div><!-- Ends p1 div-->
  <div id="test">
    <div class="subdiv">
    </div><!-- Ends subdiv div-->
  </div><!-- Ends test div-->
  <div id="contents">
    <div>
    </div><!-- Ends div-->
  </div><!-- Ends contents div-->  
</div><!-- Ends padder div-->   

Solution

  • You can use the selector #padder > div to select all div elements that are a direct child of #padder.

    Then just iterate through the elements, accessing the id using el.id (example)

    $$('#padder > div').each(function(el) {
        alert(el.id);
    });
    

    You can also map the ids to an array (example) - (without prototype.js)

    var ids = Array.prototype.map.call(document.querySelectorAll('#padder > div'), function (el, i) {
        return el.id;
    });
    

    Output:

    ["p1", "test", "contents"]