0

I am currently appending an element like so

$('#action_existing_email').append($('<option>', {
    value: templates[i].id,
    text: templates[i].name
}));

I want to append a data attribute like data-version="1"

Is there any way I can add something like data: ("foo", "bar") to get data-foo="bar"

4 Answers 4

2

Looks like you can give data as an object.

$(document.body).append($('<div>', { id: 'test1', data: { name: 'Timmy' } }));

console.log($('#test1').data('name'));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

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

Comments

1

You can simply do it like this

$('#action_existing_email').append($('<option>', {
  value: "value",
  text: "text",
  id : "opt",
  data: {
    version: 1
  }
}));

console.log($("#opt").data('version'));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="action_existing_email"></select>

P.S. Note that data-* properties are cached by jQuery internally, and they are not added as attributes to the DOM, so they are not visible:

Comments

1

Or you can simply set data-* attribute with a string like the following.

$('select').append($('<option>', {
  value: 'foo',
  text: 'foo',
  'data-version': 1
}));

console.log($('option').data('version'))
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select></select>

Comments

0

You can instead use template literals to form the HTML however you want, so that you're not limited by a third party API.

$('#action_existing_email').append(`
  <option value=${templates[i].id} data-version=1>${templates[i].name}</option>`
);

This lets you see exactly what you're appending, without having to also understand the inner workings of an API.


And of course, you're then just a step away of going fully native.

var templates = [
  {id:"foo", name:"FOO"}
];
var email = document.querySelector('#action_existing_email');

for (var i = 0; i < templates.length; i++) {
  email.insertAdjacentHTML("beforeend",
      `<option value=${templates[i].id} data-version=1>${templates[i].name}</option>`
    );
}

console.log(email.options[0].dataset.version);
<select id=action_existing_email></select>


And shorten your code by using a for-of loop instead.

var templates = [
  {id:"foo", name:"FOO"}
];
var email = document.querySelector('#action_existing_email');

for (const o of templates) {
  email.insertAdjacentHTML("beforeend", `<option value=${o.id} data-version=1>${o.name}</option>`);
}

console.log(email.options[0].dataset.version);
<select id=action_existing_email></select>

Comments

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.