简体   繁体   中英

Create new element from selector?

How can I create a new element using just a selector? (eg .myclass , #myid or a:not(.someclass) ) Basically there is no way for you to tell if the element is a div, span, li, an anchor, if it's a div with a class or with an id and so on.

In jQuery I know you can do $(selector) to get a usable DOM object. But how can this be done in JavaScript?

In jQuery I know you can do $(selector) to get a usable DOM object...

Not to create one. jQuery will do a search in the DOM for existing matches. You can do $("<div>") and such (note that's HTML, not a CSS selector) to create elements, but jQuery doesn't have a feature for creating elements from CSS selectors.

But how can this be done in JavaScript?

You'll have to parse the selector, and then use document.createElement with the tag name, and then set any classes or other things the selector describes on the new element.

CSS selectors aren't very hard to parse. You'll be able to find a lib that does it. (jQuery has Sizzle, which is a selector engine, built in and Sizzle is open source. It will naturally have code to parse selectors.)

Mootools does this.

new Element('#name.class')

yields

<div id=​"name" class=​"class">​</div>​

How can I create a new element using just a selector? (eg .myclass , #myid or a:not(.someclass) ) Basically there is no way for you to tell if the element is a div, span, li, an anchor, if it's a div with a class or with an id and so on.

In jQuery I know you can do $(selector) to get a usable DOM object. But how can this be done in JavaScript?

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