最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - What is the most efficient way of creating an HTML element and appending attributes to it and then wrapping it insi

programmeradmin2浏览0评论

I found this answer, which is great. But what If I also have to wrap another element around that element? This is how I'm doing it now:

$('#screenshots').append($('<a href="' + link + '" title="' + title + '"><img src="' + el + '" alt="" width="200px" height="200px"></a>'));

Is there a better method of doing it this way?

I found this answer, which is great. But what If I also have to wrap another element around that element? This is how I'm doing it now:

$('#screenshots').append($('<a href="' + link + '" title="' + title + '"><img src="' + el + '" alt="" width="200px" height="200px"></a>'));

Is there a better method of doing it this way?

Share Improve this question edited May 23, 2017 at 11:50 CommunityBot 11 silver badge asked Mar 1, 2012 at 6:02 nowayyynowayyy 9171 gold badge18 silver badges45 bronze badges 1
  • well, if you give it a little thought, you could create a new element the same way as in your link and appendTo... – Vigrond Commented Mar 1, 2012 at 6:05
Add a ment  | 

8 Answers 8

Reset to default 3

If you are really interested in pure speed, it's going to be hard to beat pure DOM methods:

var div = document.getElementById("screenshots"), anchor, img;
if (div) {
    anchor = document.createElement("A");;
    anchor.href = link;
    anchor.title = title;
    img = document.createElement("IMG");
    img.src = el;
    img.alt = "";
    img.width = 200;
    img.height = 200;
    anchor.appendChild(img);
    div.appendChild(anchor);
}

Your current way of appending is more efficient.

A even more efficient way, if you wish to add multiple such elements would be looping and creating strings all at one place, and then append it finally, rather than appending it on every loops.

Note that, every append or change on UI causes the browser to redraw whole page to adjust the change. So the more you postpone the UI change, more it would be efficient.

This article and this explains this exactly!!

There are other variations like (which can guide you more):

jQuery document.createElement equivalent?

I agree with linuxeasy, the original code is faster than the other suggestion to use "DOM scripting." Here is a jsperf to show the difference. I also suggest doing a document.getElementById() for further optimization.

http://jsperf./append-html-element-with-attributes

jQuery not needed.

document.getElementById("screenshots").insertAdjacentHTML("beforeend", 
        '<a href="' + link + '" title="' + title + '">\n\
            <img src="' + el + '" alt="" width="200px" height="200px">\n\
        </a>'
    );

Yes, using DOM scripting:

$("#screenshots")
    .append(
        $("<a>")
            .attr({
                'href': link,
                'title': title
            })
            .append(
                $("<img>")
                    .attr({
                        'src': el,
                        'alt': '',
                        'width': '200px',
                        'height': '200px'
                    })
            )
    );

Demo.

This is quite a mouthful, but it's so simple that you'll be hitting yourself on the head when you find out just how easy it is.

What we do is select #screenshots. We use append(), and in the function we create an a element, set its attributes using attr(), and then proceed to use append() again. In this nested append(), we create an image and set its attributes.

So, we're creating an a element, appending it to #screenshots, creating an img element, and appending that to the previously created a element.

Please note the lack of semicolon inside the append() function. It is essential that the jQuery declarations do not have the trailing semicolon or else the entire thing will not work.

Check this http://jsfiddle/T7kAS/2/

var linkElem = $("<a/>", {
    href: link,
    title: title
});

var imgElem = $("<img/>", {
    src: el,
    width: 200,
    height: 200
}).appendTo(linkElem);

$('#screenshots').append(linkElem);
var div = $("#screenshots"), anchor, img;  
anchor = $(document.createElement("A"));  
    anchor.attr("href", "link");  
    anchor.attr("title", "title");  
    img = $(document.createElement("IMG"));  
    img.attr("src", el);  
    img.attr("alt", "");  
    img.attr("width", "200");   
    img.attr("height", "200");  
    anchor.append(img);  
    div.append(anchor); 

This is the fastest way using JQuery. See this topic for more details and a benchmark: jQuery document.createElement equivalent?

The most efficient way of creating multiple elements at once is using a string to set innerHTML property on the element, because we will be deleting the creation of elements to the browser:

const el = document.createElement('div');

el.innerHTML = `
<h1>Page Title</h1>
<p>Lorem, ipsum dolor.</p>
<input value="Lorem ipsum dolor sit amet." >
<button id="btn">Click Me</button>
`;

el.addEventListener('click', () => {
  // Use target object to interact with the element
  console.log(event.target);
});

const root = document.querySelector('#app');
root.appendChild(el);
发布评论

评论列表(0)

  1. 暂无评论