senty senty - 2 months ago 8
HTML Question

extracting attributes from html using jquery

I have a string that I got from outerHTML. It logs like:

var responseHtml = jQuery(data).find("#response")[0].outerHTML;
console.log(responseHtml);

Log:

<div id="response" hello="world" big="span" hey="there">&lt;\/div&gt;"
<div class="clear"></div></div>


I am trying to get it in a format so I can access 'world' like:
values["hello"] => "world"


I am stuck here. What is the appropriate way to achieve it?

Answer

Rather than creating invalid attributes, you should be using the data attribute like:

<div id="response" data-hello="world" data-big="span" data-hey="there"></div>

And then to get those values with jquery, you can do:

var response = $('#response');
response.data('hello');  // returns "world"
response.data('big');  // returns "span"
response.data('hey'); // returns "there"

JS Fiddle

Comments