admin管理员组文章数量:1355540
I have an HTML DOM save in JavaScript Variable How I can get its attributes. Exp:
<script>
//element_html is ajax response
var element_html = '<h1 style="" class="app-control " data-order="10" data-id="48" id="heading_2_48">Heading</h1>';
var id = "heading_2_48";
var data-order="10"
</script>
How I can get these id and data-order
I have an HTML DOM save in JavaScript Variable How I can get its attributes. Exp:
<script>
//element_html is ajax response
var element_html = '<h1 style="" class="app-control " data-order="10" data-id="48" id="heading_2_48">Heading</h1>';
var id = "heading_2_48";
var data-order="10"
</script>
How I can get these id and data-order
Share Improve this question asked Jun 22, 2013 at 10:21 KalimKalim 3472 gold badges7 silver badges17 bronze badges 2- wrap it in a jquery object – A. Wolff Commented Jun 22, 2013 at 10:22
- you can access only when you append to some element. or wrap in jquery object – user2404546 Commented Jun 22, 2013 at 10:28
5 Answers
Reset to default 5Try jQuery solution:
$(element_html).attr("id");
$(element_html).attr("data-order");
Next one is even little better for performance, because its creating only one jQuery object:
var jWrapper = $(element_html);
var element_html_id = jWrapper.attr("id");
var element_html_data_order = jWrapper.attr("data-order");
Or you can try Vanilla JavaScript solution:
var d=document.createElement("div");
d.innerHTML = (element_html);
var attrs = d.firstChild.attributes;
var element_html_id = attrs["id"];
var element_html_data_order = attrs["data-order"];
(JSFiddle: http://jsfiddle/6fVdr/1/ )
var element_html = '<h1 style="" class="app-control " data-order="10" data-id="48" id="heading_2_48">Heading</h1>';
console.log($(element_html).filter('h1').attr('id'));
console.log($(element_html).filter('h1').attr('data-order'));
http://jsfiddle/tsrrR/
Works ;)
Wrap your element into Jquery Object.
var val = $(element_html).attr("id");
$(element_html).find('h1').prop('id');
$(element_html).find('h1').prop('data-order');
Updated below:
In above code find
will not work,its my mistake to understand that.
$(element_html).prop('id');
$(element_html).prop('data-order');
Thanks to "Roasted" for intimating me.
Try like this
$(element_html).find('h1').attr('id');
$(element_html).find('h1').data('order');
You can also filter with class name app-control
instead of h1
.You can also use filter
instead of find
$(element_html).filter('h1').attr('id');
$(element_html).filter('h1').data('order');
本文标签: javascriptHow to get Attributes from HTML DOM in JqueryStack Overflow
版权声明:本文标题:javascript - How to get Attributes from HTML DOM in Jquery? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1743963667a2569491.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论