2

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:

  1. It would fail on the style and title attributes because they have spaces.
  2. It might fail on the attributes with no value.
5
  • attributesStr.match(/[^\s=]+(=['][^']*['])?/g) this will get you the first split Commented Oct 4, 2017 at 13:17
  • 4
    You're making this harder than it needs to be by hacking around the pre-built string. Can you not apply the styles at the point you build that string? Or even create an object with those values to be applied later? Commented Oct 4, 2017 at 13:17
  • @RoryMcCrossan I've already found a different solution to my original problem, I was just curious if there was a way to do this in JS/JQuery :) Commented Oct 4, 2017 at 13:19
  • @tallberg Please feel free to post an answer if you think you have a solution that works :) Commented Oct 4, 2017 at 13:20
  • 1
    Sure, there's lots of ways to do anything, but most of them aren't the best way for a variety of reasons. Commented Oct 4, 2017 at 13:20

6 Answers 6

5

Take the attributesStr and insert it into the existing outerHTML. To achieve this, you need to reconstruct the node by removing the existing tag, injecting the string, and putting back the rest of the html.

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.

var element = document.getElementById('htmlElement');

var tag = element.tagName;

element.outerHTML = '<' + tag + attributesStr + element.outerHTML.substring(tag.length + 1);
<div id="htmlElement">
  The HTML element!
</div>

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

2 Comments

Wow! That really works, however if you inspect the element you'll find that it adds a new element inside the old #htmlElement. Try messing around with outerHtml to fix that.
yeah, silly jQuery's html(). might as well not use it at all
2

You can use .attr() to do this in jquery. Here is the working snippet.

click here for attr() usage

$(document).ready(function(){
$("#htmlElement").attr("class", "regularClass");
$("#htmlElement").attr("title", "Title... with spaces!");
$("#htmlElement").attr("style", "color: red; font-weight: bold");
$("#htmlElement").attr("data-attributenovalue",true);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="htmlElement">
    The HTML element!
</div>

3 Comments

I have to use a string with all the attributes, I absolutely can't modify the source format of that string. I included that attributesStr variable as an example of what the string looks like.
You want to use the string with all attributes instead of adding it separately using attr right?
Yup, works perfectly :) Thanks for answering though.
1

Try this:

var dummHTML = $("<div "+attributesStr+"></div>");   
$.each(dummHTML[0].attributes, function(i,v){
 $('#htmlElement').attr(v.nodeName,v.nodeValue);
});

Comments

1

Maybe not the best option but if its required to use the full string:

The idea is: take the content of the element, then remove it and create it again with the new attributes:

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.
var $innerHTML = $("#htmlElement").html()
$("#htmlElement").remove()
var $newElement = "<div id='htmlElement' " + attributesStr + ">" + $innerHTML + "</div>" 

$("body").after($newElement)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="htmlElement">
    The HTML element!
</div>

Comments

0

Why not separating your string with ','

var attributesStr = "";
attributesStr = attributesStr + " class='regularClass'," ; // Needs to handle key value attributes.
attributesStr = attributesStr +" title='Title... with spaces!',"; // And attributes with spaces.
attributesStr = attributesStr +" style='color: red; font-weight: bold;',"; // And style with multiple properties.
attributesStr = attributesStr +" data-attributenovalue,"; // And attributes with no value.

var array = attributesStr.split(',');

array.forEach(function(item){
 property = item.split('=');
 $('#htmlElement').attr(property[0].trim());
 if(property[1]) $('#htmlElement').attr(property[0].trim(), property[1].trim());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="htmlElement">
    The HTML element!
</div>

1 Comment

I have to use a string with all the attributes, I absolutely can't modify the source format of that string. I included that attributesStr variable as an example of what the string looks like.
0

This will get you the first split

attributesStr.match(/[^\s=]+(=['][^']*['])?/g)

result:

["class='regularClass'", "title='Title... with spaces!'", "style='color: red; font-weight: bold;'", "data-attributenovalue"]

Then in an foreach you can handle the attrs as you suggested.

1 Comment

Ok, this looks like it might work. Could you include the rest of the code to handle the attrs? Then it would indisputably 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.