<div class="twtr-tweet-text">
<p>lorem ipsum <em>date 19th nov</em></p>
</div>
<div class="twtr-tweet-text">
<p>lorem ipsum <em>date 18th nov</em></p>
</div>
<div class="twtr-tweet-text">
<p>lorem ipsum <em>date 17th nov</em></p>
</div>
如何将此块转换为下面的代码。请记住,多个块包含相同的类名等。
<div class="twtr-tweet-text">
<p><img src="speech_left.jpg" />lorem ipsum <img src="speech_right.jpg" /><em>date 19th nov</em></p>
</div>
在<em>
开始标记之前和<p>
类之后的.twtr-tweet-text{}
标记之后。
答案 0 :(得分:5)
$('.twtr-tweet-text p').prepend('<img src="speech_left.jpg" />');
$('.twtr-tweet-text em').before('<img src="speech_right.jpg" />');
答案 1 :(得分:2)
除了Scott's answer之外,您还可以使用
$('<img src="speech_left.jpg" />').prependTo($('.twtr-tweet-text p'));
<小时/> 已编辑以添加一种实现相同功能的简单JavaScript方法:
var elems = document.getElementsByTagName('p'),
leftImageSrc = 'speech_left.jpg',
rightImageSrc = 'speech_right.jpg',
className = 'twtr-tweet-text',
parent, // used in the loop, below
img; // used in the loop, below
for (i=0;i<elems.length;i++){
parent = elems[i].parentNode; // looking at two qualities of the parent,
// so storing it in a variable
if (parent.tagName.toLowerCase() == 'div' && parent.className == className){
// the 'if' tests that the parent is a div, and
// that the parent has a class-name of 'twtr-tweet-text'
// left image:
lImg = document.createElement('img');
lImg.src = leftImageSrc;
// the firstChild of the elems[i] element is the textNode
elems[i].insertBefore(lImg,elems[i].firstChild);
// right image:
rImg = document.createElement('img');
rImg.src = rightImageSrc;
elems[i].appendChild(rImg);
}
}