How do I retrieve all data-id attribute values? I have tried using jquery but only 1 id or 1 value is obtained
for my code
<div class="col text-right mr-1">
<a href="" class="show_more comment-count-custom" id="show_more" data-idpost="<?= $p["id_post"] ?>">show more comments</a>
</div>
jquery
var id = $(".show_more").data("idpost");
console.log(id)
the results that I got but only 1 id or 1 value is obtained
To build an array of the data-idpost
values from all .show-more
elements you can use map()
:
var idData = $('.show_more').map((i, el) => el.dataset.idpost).get(); console.log(idData);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="col text-right mr-1"> <a href="" class="show_more comment-count-custom" id="show_more" data-idpost="1">show more comments</a> </div> <div class="col text-right mr-1"> <a href="" class="show_more comment-count-custom" id="show_more" data-idpost="2">show more comments</a> </div> <div class="col text-right mr-1"> <a href="" class="show_more comment-count-custom" id="show_more" data-idpost="3">show more comments</a> </div>
If the show_more
class as multiple .You could use with Jquery#map()
and jquery.get()
api method
var ids = $(".show_more").map((i,elem)=> $(elem).data("idpost")).get() console.log(ids)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="col text-right mr-1"> <a href="" class="show_more comment-count-custom" data-idpost="1">show more comments</a> <a href="" class="show_more comment-count-custom" data-idpost="2">show more comments</a> <a href="" class="show_more comment-count-custom" data-idpost="3">show more comments</a> </div>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.