Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the most efficient way of creating an HTML element and appending attributes to it and then wrapping it inside of another element?

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?

like image 967
nowayyy Avatar asked Dec 30 '25 20:12

nowayyy


1 Answers

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);
}
like image 65
Scott Sauyet Avatar answered Jan 01 '26 10:01

Scott Sauyet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!