简体   繁体   中英

Can I create a DOM element without it being in the DOM using jQuery?

I have a lot of places that keep adding markup to my string that finally gets output by jQuery's append to a container. My question is - can I fake this markup being inside the DOM without it actually being there in order to perform operations such as hasClass on the item?

Yes, if you pass an HTML string to jQuery, that element (or elements) will be created inside the jQuery object, which can then be put into the DOM later:

 const $div = $('<div>someDiv</div>'); $div.addClass('foo'); console.log($div.hasClass('foo')); $('body').append($div);
 .foo { background-color: yellow; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

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