简体   繁体   中英

Convert jQuery selector to HTML for a new DOM element

I want to implement a jQuery plugin that converts a selector to HTML. I understand that the mapping between these two syntaxes is many-to-many, but simple selectors would be easy to covert to HTML.

Example:

$('div#my-id.my-class').create();

might generate:

<div id="my-id" class="my-class" />

EDIT : The purpose is to create an element if the selector returns an empty set, without having to add redundant code.

var jqs = $('div#my-id');
if(jqs.length===0) jqs = jqs.create();
var elementWillAlwaysBeThere = jqs.get(0);

i know this might not be what you are lokking for. the project zen coding is about using a css like syntax to create dom structurs. so i think lokking at there source is going to help you alot, even thou its not pure css selectores. div#wrapper>ul#imageSlider>li.image$*3 compiles to:

<div id="wrapper">
    <ul id="imageSlider">
        <li class="image1"></li>
        <li class="image2"></li>
        <li class="image3"></li>
    </ul>
</div>

so if you where to use the jQuery port you can do youre example like $.zc("div#my-id.my-class") again resulting in

<div id="my-id" class="my-class"></div>

happy source reading

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