Karolina Ticha Karolina Ticha - 3 months ago 9
HTML Question

Get attribute of each element - jQUery

why

console.log ( $("img").attr("title") );
gets only first title atribute from this?

<img src="" title="im the image" />
<img src="" title="im ass well the image" />


How can I console log title of each image?

Answer

You are only matching the first element, rather than all img tags in the DOM. To do this you can use $.each()

$("img").each(function() {
   console.log($(this).attr("title"));
});

Full example:

$("img").each(function() {
   console.log($(this).attr("title"));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<img src="" title="im the image" />
<img src="" title="im ass well the image" />

Comments