Mahendra Prajapati
Mahendra Prajapati

Reputation: 31

before img add and close anchor tag using in jquery

I have the following code

<div id="slider">    
    <img src="images/p1.jpg" />
    <img src="images/p2.jpg" />
    <img src="images/p3.jpg" /> 
</div>

I want to add <a> before and after the image tag with jQuery. This would be the result:

<div id="slider">    
    <a href="http://www.google.com"><img src="images/p1.jpg" /></a>
    <a href="http://www.google.com"><img src="images/p2.jpg" /></a>
    <a href="http://www.google.com"><img src="images/p3.jpg" /></a>    
</div>

Edit: Details from comments

So far, I have tried like this:

<span class="phone"><img src="malsup.github.io/images/p1.jpg"></span>
<span class="phone"><img src="malsup.github.io/images/p2.jpg"></span>
<span class="phone"><img src="malsup.github.io/images/p3.jpg"></span>
<span class="phone"><img src="malsup.github.io/images/p4.jpg"></span>

i have add like

$('.phone').each(function() { 
    $(this).wrapInner('<a href="test.php" />'); 
});

Additional information from comments

I want to use a different url for each image, like:

<div id="slider">
  <a href="google.com"><img src="images/p1.jpg" /></a>
  <a href="yahoo.com"><img src="images/p2.jpg" /></a>
  <a href="facebook.com"><img src="images/p3.jpg" /></a>
</div> 

Upvotes: 0

Views: 722

Answers (2)

Ahs N
Ahs N

Reputation: 8366

You can do it using the JQuery wrap() function like so:

var arr = ['https://www.google.com/', 'https://www.yahoo.com/', 'https://www.bing.com/'];

$("#slider img").each(function(index, value){
    $(this).wrap("<a href='"+arr[index]+"'></a>");
});

Here is the JSFiddle demo

Upvotes: 2

Satpal
Satpal

Reputation: 133403

Use .wrap()

Wrap an HTML structure around each element in the set of matched elements.

Here you can store different url in custom attributes which can later be used to wrap element.

$('#slider img').wrap(function() {
  return $('<a />', {
    "href": $(this).data('url'),
    "class" : "myClass"
  });
})
.myClass {
  border: 1px solid red
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="slider">
  <img src="images/p1.jpg" data-url='facebook.com' />
  <img src="images/p2.jpg" data-url='google.com' />
  <img src="images/p3.jpg" data-url='example.com' />
</div>

Upvotes: 1

Related Questions