How to get the attribute of the first child of a div?

Viewed 517

I have a div

<div id="img-1" class="cards"><img src="blah" alt="blah2"</div>

How do I define a variable that has the value of the alt attribute, without giving img a class or ID?

Thanks!

5 Answers

Try this

 const img = document.getElementById('img-1').getElementsByTagName('img')[0];
 
 console.log(img.alt);

document.getElementById('img-1').getFirstElementChild.getAttribute('alt');

You can use getFirstElementChild. As you can see it does not matter what your child element is as long as it exists. But if you are looking for alt you can simply query an img inside the div. alt is an image property.

One way is to use jQuery to select the div by class then find the first img element and get its alt attribute, then store that to a variable:

$(document).ready(function() {
    var divCards = $('.cards');
    // store the alt attribute of first image to variable
    var attrValue = divCards.find('img').eq(0).attr('alt');
    console.log(attrValue);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="img-1" class="cards">
  <img src='blah' alt='blah1'>
  <img src='blah' alt='blah2'>
</div>

firstChild.alt should do the trick:

const alt = document.querySelector('.cards').firstChild.alt;
console.log(alt);
<div id="img-1" class="cards"><img src='blah' alt='blah2'></div>

Alternatively you can use the first-child CSS selector:

const alt = document.querySelector('.cards > *:first-child').alt;
console.log(alt);
<div id="img-1" class="cards"><img src='blah' alt='blah2'></div>

var altValue = document.querySelector('.card > img').alt
for(var each of document.querySelectorAll('.card > img')){
    var altValue = each.alt;
    ....
}

JQuery equivalents

$(`.card > img`).attr('alt')

$(`.card > img`).each(function(index){ // each is bound to this
    var altValue = $(this).attr('alt');
});

> forces that the img tag lies directly below the .card element

Related