2

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?

Community
  • 1
  • 1
nowayyy
  • 917
  • 1
  • 17
  • 45
  • well, if you give it a little thought, you could create a new element the same way as in your link and appendTo... – Vigrond Mar 01 '12 at 06:05

8 Answers8

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);
}
Scott Sauyet
  • 49,207
  • 4
  • 49
  • 103
2

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?

Community
  • 1
  • 1
linuxeasy
  • 6,269
  • 7
  • 33
  • 40
2

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.com/append-html-element-with-attributes

Will Klein
  • 2,244
  • 17
  • 18
  • Also more efficient is leaving off jQuery entirely, see "Actual DOM Scripting" in the revised jsPerf: [link](http://jsperf.com/append-html-element-with-attributes/5). Whatever you do, don't make repeated calls to the jQuery factory method if you care about efficency. – Will Klein Mar 01 '12 at 22:08
1

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.

Purag
  • 16,941
  • 4
  • 54
  • 75
  • Didn't know I can set multiple attributes! I didn't even see that in the docs till now. hm. Thank you! – nowayyy Mar 01 '12 at 06:17
1

jQuery not needed.

document.getElementById("screenshots").insertAdjacentHTML("beforeend", 
        '<a href="' + link + '" title="' + title + '">\n\
            <img src="' + el + '" alt="" width="200px" height="200px">\n\
        </a>'
    );
AutoSponge
  • 1,444
  • 10
  • 7
  • This is indeed more efficient than both the original code and the currently accepted answer ("DOM scripting" with repeated calls to the jQuery factory method). – Will Klein Mar 01 '12 at 21:44
  • I just realized that insertAdjacentHTML is not supported in Firefox until Firefox 8.0. So this isn't a well-supported solution browser-wise. – Will Klein Mar 01 '12 at 22:04
  • The method has been around since before there was a FF. We have to stop accepting browser-maker failures as an excuse to not write good code. As this post points out, jQuery is too often a crutch. The proper approach is to shim the method in FF, not avoid it. – AutoSponge Mar 02 '12 at 01:11
  • Thank you, MUCH faster. Since FF does these faster updates, don't really care now. – nowayyy Mar 04 '12 at 02:03
  • Here is the updated jsPerf that includes AutoSponge's insertAdjacentHTML test: [jsPerf link](http://jsperf.com/append-html-element-with-attributes/6). It also includes another example of actual DOM scripting which is very fast but perhaps too verbose. – Will Klein Mar 04 '12 at 04:15
  • If you do this, make sure you're properly escaping your html, or else you're asking for bugs and possibly security vulnerabilities. In any case, this is slower that plain DOM, and less secure. The simplicity is deceiving; it's really easy to make invalid html or insecure code like this. – Eamon Nerbonne Feb 29 '16 at 19:04
0

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);
snnsnn
  • 10,486
  • 4
  • 39
  • 44
0

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

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

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

$('#screenshots').append(linkElem);
Malitta N
  • 3,384
  • 22
  • 30
0
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?

Community
  • 1
  • 1
Eduard
  • 3,536
  • 1
  • 20
  • 27