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
Add a ment  | 

5 Answers 5

Reset to default 5

Try 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