Get the attribute value of each element from a jQuery set, into an array

故事扮演 提交于 2020-05-10 04:44:02

问题


How can I get all attributes (e.g. href) of all elements matching a jQuery selector?


回答1:


Something like this perhaps?

var ids = [];

$('.myClass').each(function () {
  ids.push($(this).attr('id')); // ids.push(this.id) would work as well.
});



回答2:


Something like

var idArray = $(".someClass").map(function(){
    return this.id
}).get().join(',');

Working demo




回答3:


One-liner with ES6 arrow functions, using jQuery .map():

const ids = $('a.someClass').map((i, el) => el.getAttribute('href')).get();

console.log(ids);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a href="test1" class="someClass">t1</a>
<a href="test2" class="someClass">t2</a>
<a href="test3" class="someClass">t3</a>



回答4:


More simple solution with Underscore.js

For example: Get all links text who's parents have class someClass

_.pluck($('.someClass').find('a'), 'text');

Working fiddle



来源:https://stackoverflow.com/questions/5327900/get-the-attribute-value-of-each-element-from-a-jquery-set-into-an-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!