简体   繁体   中英

Create html tags with dynamic tag name in jQuery

I want to create html tags in my function like this:

function createHtmlTag(tagName) {
    var newHtmlTag = $(tagName);
    return newHtmlTag;
}

But when I call createHtmlTag('div') in my page this function return all my page div tags. I know $(tagName) causes this result, but I need to this method. I can solve this issue by these methods:

function createHtmlTagSecond(tagName) {
    var newHtmlTag = $('<' + tagName + '></' + tagName + '>');
    return newHtmlTag;
}

Using JavaScript

function createHtmlTagByJavaScript(tagName) {
    var newHtmlTag = document.createElement(tagName);
    return newHtmlTag;
}

My question

Is there a better way to use jQuery without adding additional marks like ( '<' )?

Thanks advance.

You can't avoid < or > if you want to use jQuery, but you can trim it down to var newHtmlTag = $('<' + tagName + '>');

Moreover, according to What is the most efficient way to create HTML elements using jQuery? you'd be better off using the vanilla JS approach as far as performance goes.

I found a way that I don't need to add an extra mark (combine createHtmlTagByJavaScript and createHtmlTag ).

function creatHtmlTag(tagName) {
    var newHtmlTag = $(document.createElement(tagName));
    return newHtmlTag;
}

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