This is my HTML Code:
<div class="desc">
<p>Lorem ipsum dolor sit amet,....</p>
<img src="http://sample.com/dl/image-1.jpg">
<p>Lorem ipsum dolor sit amet,....</p>
<img src="http://sample.com/dl/image-2.jpg">
<p>Lorem ipsum dolor sit amet,....</p>
<img src="http://sample.com/dl/image-3.jpg">
<p>Lorem ipsum dolor sit amet,....</p>
<img src="http://sample.com/dl/image-4.jpg">
</div>
This is my JavaScript code:
$(document).ready(function() {
$('.desc img').addClass('thumb lazyload').attr('data-src', $('.desc img').attr('src') ).attr('src','img/ui/logo/lazy.jpg');
});
I want the code to be as below, but the JavaScript code does not work:
<div class="desc">
<p>Lorem ipsum dolor sit amet,....</p>
<img class="thumb lazyload" src="img/ui/logo/lazy.jpg" data-src="http://sample.com/dl/image-1.jpg">
<p>Lorem ipsum dolor sit amet,....</p>
<img class="thumb lazyload" src="img/ui/logo/lazy.jpg" data-src="http://sample.com/dl/image-2.jpg">
<p>Lorem ipsum dolor sit amet,....</p>
<img class="thumb lazyload" src="img/ui/logo/lazy.jpg" data-src="http://sample.com/dl/image-3.jpg">
<p>Lorem ipsum dolor sit amet,....</p>
<img class="thumb lazyload" src="img/ui/logo/lazy.jpg" data-src="http://sample.com/dl/image-4.jpg">
</div>
3
Answers
This is how you can add or remove classname or can change attr
Consider the following.
This code itereates over each of the selected items and makes the change for each element. Your code is ambiguous and you may not get the results you expected.
See more: https://api.jquery.com/each/
$('.desc img').attr('src')
returns the attribute of the first element matching the selector, not the element whosedata-src
attribute is being set.You can give a function as the second argument to
.attr()
. The function will be called withthis
equal to the current element, and its return value will be used for that element.