在纯JavaScript中,这相当于什么?

时间:2010-10-09 17:31:47

标签: javascript jquery

$('<span class="pictos">j</span>').prependTo('li');

2 个答案:

答案 0 :(得分:2)

var li = document.getElementsByTagName('li');
for (var i = 0; i < li.length; i++) {
  var e = document.createElement('span');
  e.className = 'pictos';
  e.appendChild(document.createTextNode('j'));
  li[i].insertBefore(e, li[i].firstChild);
}

Working example on JSBin

答案 1 :(得分:1)

jQuery实际上做的是获取元素并为需要附加的每个父项克隆它,这样会更快,如下所示:

var span = document.createElement('span');
span.className = 'pictos';
span.appendChild(document.createTextNode('j'));

var lis = document.getElementsByTagName('li');
for (var i = 0; i < lis.length; i++) {
    lis[i].insertBefore(span.cloneNode(true), lis[i].firstChild);
}​

You can test it out here