ricks
ricks

Reputation: 3324

Jquery - How can i add a custom data attribute when appending an html element

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"

Upvotes: 0

Views: 1351

Answers (4)

user2437417
user2437417

Reputation:

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>

Upvotes: 0

Hikarunomemory
Hikarunomemory

Reputation: 4305

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>

Upvotes: 1

Sanchit Patiyal
Sanchit Patiyal

Reputation: 4920

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:

Upvotes: 1

Taplar
Taplar

Reputation: 24965

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>

Upvotes: 2

Related Questions