aa003
aa003

Reputation: 131

How to Add class to all images inside div using jQuery?

Inside div I am dynamically loading inner text and it also contains img tags. After rendering dynamically I want to add class to all images present insdie that div.

I have tried this but its not working for me.

src of every img tag inside div is starting from data:image

function loadDiv() {

         // loading successfully div elements

          $("img[src*=data:image]").addClass("img-responsive");


     }

Upvotes: 2

Views: 6699

Answers (2)

user1752532
user1752532

Reputation:

An alternative answer for a conditional on the data- attribute

$(function() {
  var img = $('img');
  img.attr('src') === 'data:image' ? img.addClass("img-responsive") : img.addClass("another-class");
});
img {
  height: 100px;
  width: 100px;
  display: inline-block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<img src="data:image" />
<img src="data:image" />
<img src="data:image" />
<img src="data:image" />
<img src="data:image" />
<img src="data:image" />
<img src="data:image" />

Upvotes: 0

Shaunak D
Shaunak D

Reputation: 20636

Either use '' to enclose the attribute value

$("img[src*='data:image']").addClass("img-responsive");

or escape the :

$("img[src*=data\\:image]").addClass("img-responsive");

*Some special characters are used by jQuery filters/selectors; so they need to be escaped to form an expession

Upvotes: 13

Related Questions