简体   繁体   中英

How do you create an element with jQuery?

Do you create it like this: $('<div />') or $('<div></div>')

Is that how you create an element? Thanks.

Either way works just fine. Just don't forget to insert in the dom - you can use appendTo(selector) .

var $my_elem = $("<div/>").appendTo(document.body);
var $my_elem = $("<div class='abc'></div>").appendTo(document.body);

Then you have $my_elem represending the inserted element.

$('YOUR SELECTOR').append('<div />');

The <div /> will create a <div></div>

You can include classes, id's and other attributes, jQuery should figure it out and rap it up.

I included use of the append function because you are probably going to want to insert it somewhere. There is a number of similar functions you could use instead.

Looking at the jQuery source code , it looks like anything matching the regular expression /^<(\\w+)\\s*\\/?>(?:<\\/\\1>)?$/ will be interpreted as a "single tag" and passed directly to document.createElement (assuming no context is specified). Therefore, at least in the current implementation, there's no difference (behavior or performance) between the various formats.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM