naser
naser

Reputation: 171

How to add div in new tag with jQuery

Consider the following code:

<div class="left">
    <img class="img" src="stone1.png"/>
</div>
<div class="center">
    <img class="img" src="stone2.png"/>
</div>
<div class="right">
    <img class="img" src="stone3.png"/>
</div>

Now, I want to create this tag whit jQuery:

<a href="#" data-r="start" data-a="fade"></a>

and put each of div in tag a to create this code:

<a href="#" data-r="start1" data-a="fade">
    <div class="left">
        <img class="img" src="stone1.png"/>
    </div>
</a>
<a href="#" data-r="start2" data-a="fade">
    <div class="center">
        <img class="img" src="stone2.png"/>
    </div>
</a>
<a href="#" data-r="start3" data-a="fade">
    <div class="right">
        <img class="img" src="stone3.png"/>
    </div>
</a>

How do it?

Upvotes: 2

Views: 82

Answers (5)

Arun P Johny
Arun P Johny

Reputation: 388316

Use .wrap()

$('.left, .center, .right').wrap(function(idx){
    return '<a href="#" data-r="start' + (idx + 1) + '" data-a="fade"></a>'
})

Demo: Fiddle

Upvotes: 2

William Buttlicker
William Buttlicker

Reputation: 6000

Try this:

$('.left').wrapAll('<a href="#" data-r="start" data-a="fade">');

Upvotes: 0

Dineshkani
Dineshkani

Reputation: 3015

Use like this

var i = 1;
$("div").each(function(){
var elem = $("<a/>").html(this);

elem.attr("href","#");
elem.attr("data-r","start"+i);
elem.attr("data-a","fade");

i++;console.log(elem);
});

See Demo

Upvotes: 0

Konstantin Dinev
Konstantin Dinev

Reputation: 34895

Try this code:

$('.img').parent().wrap('<a href="#" data-r="start" data-a="fade"></a>');

It selects all the parent elements of element with class .img and wraps the element in the specified markup.

Upvotes: 0

Sushanth --
Sushanth --

Reputation: 55750

You can use .wrap method

 $('div').each(function(i) {
      $(this).wrap('<a href="#" data-r="start'+ (i+1) + '" data-a="fade">');
 });

Check Fiddle

Upvotes: 4

Related Questions