Search code examples
javascriptarrayssizzle

Get divs into array with Sizzle and JS


<div class="item">
   <div id="itemid">001</div>
   <div id="itemname">name 1</div>
</div>

<div class="item">
   <div id="itemid">002</div>
   <div id="itemname">name 2</div>
</div>

I am using the Sizzle Library to get this data off the page. There is (n) number of items possible.

myVar = Sizzle('.item');

Is there any way to get this data into an array

[0] itemid => 001
    itemname=> name 1


[1] itemid => 002
    itemname => name 2

I need to get each of the items into an array, Without using jQuery. and i do know the name of the DIV's within each item


Solution

  • With the Sizzle library as a dependency the following will iterate all the <div class="item"> parents and then iterate all the children of each parent.

    <script type='text/javascript' src='https://raw.github.com/jquery/sizzle/master/sizzle.js'></script>
    <script type='text/javascript'>
        var itemDivs = Sizzle('.item')
        var items = []
        for (var i = 0; i < itemDivs.length; i++) {
            var children = Sizzle('div', itemDivs[i])
            var item = {}
            for (var j = 0; j < children.length; j++) {
                item[children[j].id] = children[j].innerText || children[j].textContent
            }
            items.push(item)
        }
    
        console.log(items)
    </script>
    

    If your HTML has other elements, the above code will need modifying to only find the specific children needed for the array. The HTML this was tested against is:

    <div class="item">
       <div id="itemid">001</div>
       <div id="itemname">name 1</div>
    </div>
    
    <div class="item">
       <div id="itemid">002</div>
       <div id="itemname">name 2</div>
    </div>
    

    and the output I get in Chrome DevTools console is

    [Object, Object]
    0: Object
        itemid: "001"
        itemname: "name 1"
        __proto__: Object
    1: Object
        itemid: "002"
        itemname: "name 2"
        __proto__: Object
        length: 2
        __proto__: Array[0]