Andy Andov Andy Andov - 5 months ago 7
HTML Question

Get element id by data attribute

I have following html output :

...
<ul id="commentlist">
<li id="comment-12" data-post="post-1">Comment 1 for post 1</li>
<li id="comment-34" data-post="post-1">Comment 2 for post 1</li>
<li id="comment-56" data-post="post-1">Comment 3 for post 1</li>
</ul>
<ul id="commentlist">
<li id="comment-78" data-post="post-2">Comment 1 for post 2</li>
<li id="comment-90" data-post="post-2">Comment 2 for post 2</li>
</ul>
...


Please help me to generate 2 dementional array (like below) with jQuery:

array = [
"post-1": ["comment-12", "comment-34", "comment-56"],
"post-2": ["comment-78", "comment-90"]
]


I've tried:

jQuery("li[data-post]").each(function(){
/*console.log(jQuery(this)); -- this contains necessary "id" but I don't know how to fetch it*/

var testdata = jQuery(this).data('post');
if (comment_lists.indexOf(testdata) == -1)
comment_lists.push(testdata);
});

Answer

Use each() method to iterate over elements and generate object inside based on the data attribute.

var obj = {};

// select elements with the attribute and iterate
$('[data-post]').each(function() {
  // get data attribute value
  var d = $(this).data('post');
  // define the property if not already defined
  obj[d] = obj[d] || [];
  // push the id of element
  obj[d].push(this.id)
})

console.log(obj)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="commentlist">
  <li id="comment-12" data-post="post-1">Comment 1 for post 1</li>
  <li id="comment-34" data-post="post-1">Comment 2 for post 1</li>
  <li id="comment-56" data-post="post-1">Comment 3 for post 1</li>
</ul>
<ul id="commentlist">
  <li id="comment-78" data-post="post-2">Comment 1 for post 2</li>
  <li id="comment-90" data-post="post-2">Comment 2 for post 2</li>
</ul>

Comments