luckytwotimes
luckytwotimes

Reputation: 41

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

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!

Upvotes: 3

Views: 1457

Answers (5)

Spectric
Spectric

Reputation: 31987

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>

Upvotes: 0

Hassan Faghihi
Hassan Faghihi

Reputation: 2021

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

Upvotes: 0

Nathaniel Flick
Nathaniel Flick

Reputation: 2963

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>

Upvotes: 0

Ritesh Waghela
Ritesh Waghela

Reputation: 3727

Try this

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

Upvotes: 1

Tushar Shahi
Tushar Shahi

Reputation: 20376

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.

Upvotes: 0

Related Questions