I have a string of attributes written in valid html, and I want to put those attributes on an actual html element (not a html string of an element).
For example, I have the string of attributes in the sensibly named attributesStr variable, and I want to add those attributes to the #htmlElement div.
var attributesStr = "";
attributesStr += " class='regularClass'"; // Needs to handle key value attributes.
attributesStr += " title='Title... with spaces!'"; // And attributes with spaces.
attributesStr += " style='color: red; font-weight: bold;'"; // And style with multiple properties.
attributesStr += " data-attributenovalue"; // And attributes with no value.
// Your special code to add the attributes to `#htmlElement` goes here.
<div id="htmlElement">
The HTML element!
</div>
After the JQuery / JavaScript code is run, #htmlElement should look like:
<div id="htmlElement" class='regularClass' title='Title... with spaces!' style='color: red; font-weight: bold;' data-attributenovalue>
The HTML element!
</div>
How can I do this in JavaScript or Jquery?
First attempt: I was thinking I could do this by .split()ing attributesStr on spaces, and then splitting each individual attribute key value pair on the =, and then iterating that array and adding each key value pair with JQuery's .prop() or .attr(), but this wouldn't work for two reasons:
- It would fail on the
styleandtitleattributes because they have spaces. - It might fail on the attributes with no value.
attributesStr.match(/[^\s=]+(=['][^']*['])?/g)this will get you the first split