I have to create the following type of HTML structure:
<div id="dcontent">
<ul class="thm">
<li><a href="#"><img src="img/theme1.jpg" id="t1" border="none"/></a></li>
<li><a href="#"><img src="img/theme2.jpg" id="t2" border="none"/></a></li>
<li><a href="#"><img src="img/theme3.jpg" id="t3" border="none"/></a></li>
I need to create 18 nested images this way so I use the following Javascript loop:
for (var count = 1; count < 19; count++) {
newLi = document.createElement('li');
newLi.setAttr开发者_如何学编程ibute('id', 'l' + count);
newLink = document.createElement('a');
newLink.setAttribute('href', '#');
newLink.setAttribute('id', 'a' + count);
$(newLink).appendTo('#l' + count);
newImg = document.createElement('img');
newImg.setAttribute('src', thumbPath + count + '.jpg');
newImg.setAttribute('id', 't' + count);
newImg.setAttribute('border', 'none');
$(newImg).appendTo('#a' + count);
$(newLi).appendTo('.thm');
}
The code outputs only li
nested in ul
which is nested in div
. Is it better to use jQuery because I read that document.createElement
(pure Javascript) is faster method. Any help will be greatly appreciated.
You don't need any jQuery at all.
You can replace the appendTo
functions as well, with
var parent = document.getElementById("id");
parent.appendChild(child);
var $thm = $('.thm');
for(var count=1; count<19; count++)
{
var $li = $('<li><a href="#"><img src="img/theme' + count + '.jpg" id="t' + count + '" border="none"/></a></li>')
$thm.append($li);
}
jQuery is a set of abstractions to ease your work with JavaScript. This does mean you will perform extra logic to perform the same task.
You need to find a balance between performance at runtime and the time it takes for you to develop.
精彩评论