The input element jQuery.before () and .after () are not working properly, what am I doing wrong?

I am trying to dynamically surround sets of IMG and A tags with a div tag, but I cannot get it to 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 result:

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

What I'm 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>');  

to make sure it was unable to execute .next () code. after (), but it works fine. I am new to using jQuery and cannot understand what I am doing wrong. Can anyone help? You are welcome.

+3
source share
2 answers

You can use .wrapAll(), for example:

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

, <img> <a>, <div>.

+3

() ( ):

$('img.myClass-1').next().andSelf().wrapAll('<div style="position: relative;" />');
+1

Source: https://habr.com/ru/post/1768260/


All Articles