Reputation: 1046
I have the following html code:
<p>adfa</p>
<p><img src="http://localhost:27756//download.jpg" alt="" width="282" height="179" /></p>
<p>adfa</p>
<p><img src="http://localhost:27756/Summit 2013-5.jpg" alt="" width="358" height="358" /></p>
<p>adfa</p>
Now I want to add height and width of each image to its src. How can I do that? I am very new to jQuery.
Upvotes: 0
Views: 79
Reputation: 6217
$("img").each(function(idx, e) {
$(this).attr("src", $(this).attr('src') + '?width=' + $(this).attr('width') + '&height=' + $(this).attr('height'));
});
fiddle here: https://jsfiddle.net/y794tazy/
To use the true images width and height (since this can be different than what the attributes are set at), you could do this:
$("img").each(function(idx, e) {
$(this).attr("src", $(this).attr('src') + '?width=' + $(this).width() + '&height=' + $(this).height());
});
Upvotes: 1
Reputation: 6081
try something like this:
$('img').each(function() {
alert($(this).attr('src'));
$(this).css('width',500);
$(this).css('height',500);
});
If you want to add to img
attribute you can do like:
$('img').each(function(i) {
alert('OLD:Width for image at index '+i+' is '+$(this).attr('width'));
alert('OLD:height for image at index '+i+' is '+$(this).attr('height'));
$(this).attr('width',500);
$(this).attr('height',500);
alert('NEW:Width for image at index '+i+' is '+$(this).attr('width'));
alert('NEW:height for image at index '+i+' is '+$(this).attr('height'));
});
Demo Fiddle: https://jsfiddle.net/eqr5s9ac/
Upvotes: 1
Reputation: 2632
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-1.12.3.min.js" integrity="sha256-aaODHAgvwQW1bFOGXMeX+pC4PZIPsvn2h1sArYOhgXQ=" crossorigin="anonymous"></script>
<script type='text/javascript'>
function addDimensionsToSrc(){
jQuery("img").each(function(idx,el){
el.src = el.src + "?height=" + el.height + "&width=" + el.width;
});
}
</script>
</head>
<body>
<p>adfa</p>
<p><img src="http://localhost:27756//download.jpg" alt="" width="282" height="179" /></p>
<p>adfa</p>
<p><img src="http://localhost:27756/Summit 2013-5.jpg" alt="" width="358" height="358" /></p>
<p>adfa</p>
</body>
</html>
Upvotes: 1