Home > OS >  How to get unique alt value from separate images?
How to get unique alt value from separate images?

Time:07-07

I want to create a function that will retain the alt value, so that I can take the name of a movie and transport it to the next webpage.

<div >
   <ul >
      <li>
         <img id="a" src="/images/movie-a.jpg" alt="Movie A">
         <button><a href="/html/bookticket.html" onClick="getMovieName()">BOOK</a></button>
      </li>
      <li>
         <img id="a" src="/images/movie-b.jpg" alt="Movie B">
         <button><a href="/html/bookticket.html" onClick="getMovieName()">BOOK</a></button>                      
      </li>
      <li>
         <img id="a" src="/images/movie-c.jpg" alt="Movie C">
         <button><a href="/html/bookticket.html" onClick="getMovieName()">BOOK</a></button>
      </li>
   </ul>
</div>

I'm aware that I have the same id name for each item, however I have 14 films in total at the moment, so I would like to have a single function that can get each items unique alt value. Currently, no matter which movie link I click, it shows me 'Movie A' using the following function:

function getMovieName() {
    let link = document.getElementById('a');
    let movieInfo = [];
    movieInfo.push(link.alt);
    console.log(movieInfo);
};

CodePudding user response:

You can detect which A was clicked (and find the matching IMG tag) from the structure of the LI.

function getMovieName(e) {
    e.preventDefault();  // stop the browser from immediately going to a.href
    let link = e.target; // the link that was clicked
    let img = link.closest("li").querySelector("img"); // the img that is in the same grandparent "li" tag as the link that was clicked
    console.log(img.alt);
};
<div >
   <ul >
      <li>
         <img src="/images/movie-a.jpg" alt="Movie A">
         <button><a href="/html/bookticket.html" onClick="getMovieName(event)">BOOK</a></button>
      </li>
      <li>
         <img src="/images/movie-b.jpg" alt="Movie B">
         <button><a href="/html/bookticket.html" onClick="getMovieName(event)">BOOK</a></button>                      
      </li>
      <li>
         <img src="/images/movie-c.jpg" alt="Movie C">
         <button><a href="/html/bookticket.html" onClick="getMovieName(event)">BOOK</a></button>
      </li>
   </ul>
</div>

CodePudding user response:

Your HTML is invalid, each ID should be unique.

Your code doesn't work, because .getElementById returns first element found.

Just use a different id for each movie

  • Related