开发者

jquery get attributes

I'm looking for a way to grab the custom attribute开发者_StackOverflow中文版s of a element with jquery.

<span id='element' data-type='foo' data-sort='bar'></span>

I'm looking to get: ["data-type", "data-sort"] as an array.

Anyone know how to do this?

Thanks.


You can use the .attributes DOM property and loop through, like this:

var arr = document.getElementById('element').attributes, attributes = [];
//or if you're inside a jQuery loop, just use this.attributes
//e.g.: var arr = $("span").get(0).attributes, attributes = [];
for(var i = 0; i < arr.length; i++) {
  if(arr[i].name.indexOf("data-") == 0) //only ones starting with data-
    attributes.push(arr[i].name);
}
alert(attributes); ​//use it for something, result is ["data-type", "data-sort"]

You can see a working demo here, aside from grabbing the element, this isn't jQuery specific at all, so you could easily remove it completely if needed.


Just for reference for those using jQuery, attributes starting with 'data-' can be accessed by the data() function:

<span id='element' data-type='foo' data-sort='bar'></span>

var el = $('#element');
return [el.data('type'), el.data('sort')];

Some browsers are starting to store these in more advanced ways (local data storage?) and others are not, but it seems to work pretty well. Note that W3C validators don't like expando attributes like this, but I think there are some proposals to standardize this so they do validate. The last time I researched the best way to store data with an element, using data-key like this was one of the winners among professionals.

Another way I ran across to tie data to an element is to insert a script tag immediately before or after the element, giving it a type other than text/javascript such as:

<script id="templatedata" type="text/html">
   <span>23</span>
   <span>Alfred</span> <!-- I'm sure you can get more creative than I'm being here -->
</script>

This will not be displayed in the browser, and you can still get the HTML in there via $('#templatedata').html();. This may still have its problems as technically it's not correct, but if W3C HTML validation is important to you it may be a viable option.


just simply $('#element').attr('data-type'); and $('#element').attr('data-sort');

sorry, answered before read the whole question :-/ don't think there's a built in functionality to get them as an array, get the first, get the second and then build the array manually.


You can use this code, its very simple to search. Just include jquery nothing else.. Simple Jquery Filter

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜