views:

47

answers:

2

I am trying to dynamically surround sets of IMG and A tags with a div tag but am unable to make it work.

my html:

<img class="myClass-1" src="img5" />
<a class="myClass-2" href="url"></a>  

my script:

$('img.myClass-1').each(function(){
   $(this).before('<div style="position: relative;">');
   $(this).next().after('</div>');
});  

my Firebug outcome:

<div style="position: relative;"/>
<img class="myClass-1" src="img5" />
<a class="myClass-2" href="url"></a>  

What I am trying to accomplish:

<div style="position: relative;">
<img class="myClass-1" src="img5" />
<a class="myClass-2" href="url"></a>
</div>  

I replaced

$(this).next().after('</div>');  

with

$(this).next().after('<p>test</p>');  

just to see if it was unable to execute the .next().after() code but it works fine. I am new to using jQuery and can't figure out what I'm doing wrong. Can somebody help? Please.

+3  A: 

You can use .wrapAll(), like this:

$(this).next().andSelf().wrapAll('<div style="position: relative;" />');

You can test it out here, this takes <img> and <a> then wraps them both in that <div> container.

Nick Craver
jQuery is very semantic. I am impressed that you can write code like that with it. (I'm trying to move away from prototype towards jQuery.)
Alin Purcaru
WOW! This works great! Thank you so much. How do you find out that there is (and can use things like) .andSelf().wrapAll(...) ?
Angie
@Angie - The API site has all methods and what they're for :) http://api.jquery.com/ You learn by needing/finding them I suppose, that's how I go anyway :)
Nick Craver
Angie
+1  A: 

You could also get rid of the each() (or just replace this with your selector in Nick's snippet):

$('img.myClass-1').next().andSelf().wrapAll('<div style="position: relative;" />');
alex
Yes, thank you.
Angie