添加自定义属性createdElement - jQuery

add custom attribute to createdElement - jQuery

本文关键字:jQuery createdElement 自定义属性 添加      更新时间:2023-09-26

我使用createElement将其替换为附加的大块html代码。我知道我可以很容易地添加id, class, style:

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

但是,如何使用这种方法添加子id呢?

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

如果你正在使用jQuery,那么我相信你正在寻找这样的东西:

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));

使用createElement方法将花费更多的时间来编程(但应该比jQuery更快)。至于在createElement方法中使用子id,请查看Element对象的API

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