2
<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

Dennis
  • 32,200
  • 11
  • 64
  • 79
eleven11
  • 362
  • 2
  • 3
  • 12

1 Answers1

2

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]
andyb
  • 43,435
  • 12
  • 121
  • 150
  • 1
    Happy to help :-) I've just updated the code to work in Firefox, which uses `textContent` instead of `innerText` - see http://stackoverflow.com/a/1359507/637889 – andyb Mar 14 '13 at 12:04
  • Also note that `innerText` was left in to support IE. Firefox, Safari and Chrome all support the W3C standard `textContent` – andyb Mar 14 '13 at 12:06
  • Thanks a lot for that - you have made my day go a lot smoother! – eleven11 Mar 14 '13 at 15:12