senty
senty

Reputation: 12857

add custom attribute to createdElement - jQuery

I am using createElement to replace it with appending big chunk of html code. I understand I can add id, class, style easily with:

var container = 'container';

container.className = 'item';
container.style.cssText = 'color: red';

However, how can I add sub-id using this approach?

<div class="container">
    <i class="item" sub-id="item-19"></i>
</div>

Upvotes: 1

Views: 32

Answers (1)

ioneyed
ioneyed

Reputation: 1102

If you are using jQuery then I believe you are looking for something like this:

var container = $('<div />').attr('class','container');
var subId = $('<i />').attr({ 'class':'item', 'sub-id':'item-19'}).text('italic');

//append it to the body

$('body').append(container.append(subId));

Using the createElement methods would be more time consuming to program (but should be faster than jQuery). As for using the sub id in your createElement methods take a look at the API for an Element Object

container.setAttribute("sub-id", "item-19");

Upvotes: 2

Related Questions