Get an element of a class with Javascript

1

I want to get an HTML element that is with a class, but that same class is in other elements.

<img class="imagens-noticias" src="imagens-noticias/noticia-1.png" alt="imagem">

<img class="imagens-noticias" src="imagens-noticias/noticia-2.png" alt="imagem">

<img class="imagens-noticias" src="imagens-noticias/noticia-3.png" alt="imagem">

Is it possible to get the first image without affecting others using pure JavaScript?

    
asked by anonymous 28.06.2018 / 05:03

1 answer

3

Yes, using:

document.querySelectorAll(".imagens-noticias")[0];

Or:

document.getElementsByClassName("imagens-noticias")[0];

document.querySelectorAll selects all elements that have the same class by creating a node list (node list) where you can select one by its index, where [0] is first, [1] is the second and so on.

The same behavior has document.getElementsByClassName . The difference between the one and the other is that it accepts CSS selectors, which makes the selection of elements much more flexible ( learn more in this documentation ).

    
28.06.2018 / 05:11