2

So I have a list of attributes stored as a string variable. I want to add that variable to a <div>. I'm currently at a loss. What I have is as follows:

HTML:

<div></div>

JS:

var attributes = 'data-id="123" data-type="content" data-order="1"'

Desired Output:

<div data-id="123" data-type="content" data-order="1"></div>

1
  • 1
    Since your attributes are stored as a string, you need to first extract your data attributes and their values, loop through them, and then add them to your div, which you can do with jQuery's .data() method. Commented Feb 15, 2017 at 17:35

4 Answers 4

2

This should work.

var div = document.getElementById('YOUR_ID');
var attributes = 'data-id="123" data-type="content" data-order="1"'
attributes.split(' ').forEach((attr) => {
   div.setAttribute(attr.split('=')[0], attr.split('=')[1]);
});
Sign up to request clarification or add additional context in comments.

3 Comments

You would need to get rid of the double quotes in the data values though.
This breaks if there's a space inside an attribute value.
This also worked for my use, Thanks for contributing. The others were just a little more bulletproof.
2

split the attributes string by spaces (but not spaces inside the quotes)

var div = document.getElementById('test');
var attributes = 'data-id="123" data-type="content new" data-order="1"';
var arr = attributes.match(/[^\s="']+|"([^"]*)"|'([^']*)'/g);

for (var i = 0; i < arr.length; i += 2)
  div.setAttribute(arr[i], arr[i + 1].replace(/"/g, ''));
<div id="test">test</div>

Comments

1
var attributes = 'data-id="123" data-type="content" data-order="1"';
 attributes=attributes.split(" ");
i=0;
var d=document.getElementsByTagName('div')[0];
while (i<attributes.length){
d.setAttribute(attributes[i].split('=')[0],attributes[i].split('=')[1].replace(/\"/g,""));
i++;
}

alert(d.getAttribute("data-id"));

Comments

1

You can use split() to split attributes on key-value and then use forEach() loop to add them to element.

var attributes = 'data-id="123" data-type="content" data-order="1"'.replace(/"/g, '').split(/=| /)
attributes.forEach(function(e, i) {
  if(i % 2 == 0) $('div').attr(attributes[i], attributes[i + 1])
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>DIv</div>

3 Comments

On every even number do something.
Right, but why only even numbers?
In fist case element from attributes with i or 0 is key and i + 1 or 1 is value, etc...

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.