Trying to wrap an tag around an image, addClass and input src of img as href of tag:
$(document).ready(function() {
$(".new img").each(function() {
var src = $(this).attr('src').addClass('image');
var a = $('<a/>').attr('href', src);
$(this).wrap(a);
});
});
My HTML:
<img class="new" src="pic0.png" title="Image_Title"/>
Can't seem to get this to work. Any suggestions would be helpful!
Think of an a tag as a box that wraps the element. you can think of it as an invisible border around and including everything within. if you wrap an image in an a tag the image is clickable, it will direct you to the href of the a tag. So if you want the image to click to the source of the image.
To create an image link, you combine an <a> tag (i.e. link) with an <img> tag (i.e. image). You simply "wrap" the link code around the image code.
Two things. Firstly, you have your selector backwards -- it should be img.new
. Secondly, attr
returns a string, not jQuery, so you can't chain it. Do the following and it should work:
$(document).ready(function() {
$("img.new").each(function() {
var $this = $(this);
var src = $this.attr('src');
$this.addClass('image');
var a = $('<a/>').attr('href', src);
$this.wrap(a);
});
});
Your selector just needs an adjustment, this:
$(".new img")
Should be:
$("img.new")
The new
class is on the <img>
itself, the <img>
isn't a descendant of a class="new"
element, which is what your current selector is looking for. Also .attr('src')
gets a string, so you need to add the class before calling it, overall like this:
$(function() {
$("img.new").each(function() {
var src = $(this).addClass('image').attr('src');
var a = $('<a/>').attr('href', src);
$(this).wrap(a);
});
});
You can test it here, or a bit simpler/faster version here:
$(function() {
$("img.new").each(function() {
var a = $('<a/>').attr('href', this.src);
$(this).addClass('image').wrap(a);
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With