PDA

View Full Version : How can I add a <span> around <img />


Kagura-San
03-14-2008, 12:14 PM
Hi,

I'm trying to add some progressive enhancements to my wordpress theme by encapsulating all <img /> elements in my <div class="entry"> with a <span>.

So, before JavaScript fires up, this is what I'm working with:

<div class="entry">
<img src="/test.jpg" alt="testing" /> Test sentence
</div>


After JavaScript does it's work, this is what I'd like to end up with:

<div class="entry">
<span class="thumbnail"><img src="/test.jpg" alt="testing" /></span> Test sentence
</div>


This is how far I got without help:

enhanceThumbnails = function() {
var e = document.getElementsByClassName('entry');
for(i=0;e.length > i;i++) {
var t = e[i].getElementsByTagName('img');
if(t.length > 0) {
// alert(t[0].alt);
}
}
}


I can successfully browse through DOM to get to the images, but I have no idea how to prepend <span class="thumbnail"> and append </span> to the image itself.

Any ideas?

shyam
03-14-2008, 01:41 PM
var img = t[j]; // inner loop
var s = document.createElement('span');
var p = img.parentNode;
s.appendChild(img.cloneNode(true));
s.className = 'thumbnail';
p.replaceChild(s, img);

Kor
03-15-2008, 01:35 PM
But you do you need to complicate the code with an extra SPAN? What's the use/reason?