-2

<label for="s1" id="slide1"><img class="topCard" src="https://via.placeholder.com/150.png" alt="example"></label>

I want to get "alt" and "src" from img tag in this label by javascript. I had selected the label by javascript and put it in a variable like this:

let label = document.querySelector(selector);

how to get "alt" and "src" from img tag in this label by javascript?

Kevin Hernández
  • 704
  • 10
  • 25
mahdi
  • 1
  • 3
  • 2
    Familiarize yourself with the [DOM API](https://developer.mozilla.org/en-US/docs/Web/API/Document_Object_Model). What is `selector`? Why are you only selecting the label and not the image directly? Are you aware of the `getAttribute` method or how to get properties of elements? By the way, to get only the file name from the `src` property, see [javascript onclick get image name without path](https://stackoverflow.com/q/29182283/4642212#comment118324199_29182283). – Sebastian Simon Apr 19 '21 at 19:02

2 Answers2

3

let label = document.querySelector('img');
console.log(label.getAttribute('src'));
<label for="s1" id="slide1"><img class="topCard" src="/A-Z/G.png" alt="G"></label>
peinearydevelopment
  • 11,042
  • 5
  • 48
  • 76
  • I have a lot of img tag and I can't do querySelector on it. I want to get access to just content of that particular img in that label. – mahdi Apr 20 '21 at 04:04
0

After we have label tag, we can get img tag in it by "getElementsByTagName". like this:

let img = label.getElementsByTagName('img')[0];
let alt = img.getAttribute('alt'); 
mahdi
  • 1
  • 3