amit munde
amit munde

Reputation: 43

while getting image src using jquery returns undefined

$(document).ready(function() {
  var aa = $('.page-1 img').attr('src');
  alert(aa);
});
<!DOCTYPE html>
<html>

<head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>

<body>
  <img src="dddddd.jpg" width="76" height="100" class="page-1" />
</body>

</html>

while getting image scr using jquery returns undefined can anyone solve this problem?

Upvotes: 0

Views: 511

Answers (2)

Ayaz Ali Shah
Ayaz Ali Shah

Reputation: 3531

You are using selector in wrong way. That's why script is return error. Since .page-1 is on the same element you need select it by following pattern.

$('img.page-1').attr('src');

<script>
$(document).ready(function(){
  var aa= $('img.page-1').attr('src');
  alert(aa);
});
</script>
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<img src="https://www.google.ae/images/branding/googlelogo/2x/googlelogo_color_120x44dp.png" width="76" height="100" class="page-1" />
</body>
</html>

.page-1 img this method will find the child img element of .page-1. Since it is not and there is no child element so selector won't work.

Upvotes: 0

void
void

Reputation: 36703

Your selector should be img.page-1.

.page-1 img will try to find img tag inside an element with class .page-1.

$(document).ready(function() {
  var aa = $('img.page-1').attr('src');
  alert(aa);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<img src="https://placebear.com/g/200/300" width="76" height="100" class="page-1" />

Upvotes: 2

Related Questions