1

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

2
  • wrap it in a jquery object Commented Jun 22, 2013 at 10:22
  • you can access only when you append to some element. or wrap in jquery object Commented Jun 22, 2013 at 10:28

5 Answers 5

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.net/6fVdr/1/ )

Sign up to request clarification or add additional context in comments.

Comments

3
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.net/tsrrR/

Works ;)

1 Comment

@roasted ... yes i edited it and posted a fiddle for it - based on your comment - so it works
3

Wrap your element into Jquery Object.

var val = $(element_html).attr("id");

Comments

3
$(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.

2 Comments

@roasted:may I know reason ?
Because .find() is looking for descendants, h1 here is not descendant of wrapped object: jsfiddle.net/nLL5h To use .find() you would need something like that: $('<div/>').html(element_html).find('h1').prop('id')
3

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');

2 Comments

Thanks Boss I got another great idea from your answer .data('order');
Thnks for the suggestion @roasted I have edited my ans...and I think find will also will work

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.