Cunning Cunning - 10 months ago 26
HTML Question

Creating an object using filtered element attributes in JavaScript

I have a dynamically created

area like this

<div class="canvas">
<div id="1" data-level="0" data-tag="a"></div>
<div id="2" data-level="0" data-tag="b">
<div id="3" data-level="1" data-tag="b">
<div id="4" data-level="2" data-tag="a"></div>
<div id="5" data-level="1" data-tag="a"></div>
<div id="6" data-level="0" data-tag="b"></div>

I want to create an object to pass in an ajax call containing ids, tags and texts on each
element with

Something like this

var outObj = jQuery('div.canvas > div[level="0"]')
{attr: 'id', prop: 'id'},
{attr: 'data-tag', prop: 'tag'}

That would result in

{ id: "1", tag: "a" },
{ id: "2", tag: "b" },
{ id: 6, tag: "b" }


You can do it using .map()

Try like this

var outObj = $('div.canvas > div[data-level="0"]').map(function() {
  return {
    id: $(this).attr("id"),
    tag: $(this).data("tag")