Picking up an element of a class with Javascript

Asked

Viewed 1,398 times

1

I want to take 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">

There is the possibility to grab the first image, without affecting the others using pure Javascript?

  • 2

    Yes: document.querySelector('.imagens-noticias'); takes the first element.

1 answer

3


Yes, using:

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

Or:

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

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

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

  • rsrs.. how so?

  • ah tah.... simmm. tb works

  • All....

  • It works well, but in my view this selector is capenga, because the interesting thing is to select the collection. But it works tb. It is a matter of criteria. I like to select the collection.

  • If you want to post a nice answer I remove mine, no problem.

  • No, I would not answer. That’s why I commented on.

  • Why? Just like to comment? If you want to answer, no problem.

  • It’s just that I was trying to remember if I’d ever seen a similar question, but sometimes I prefer to look to see if there’s something new that I haven’t seen yet.

  • It worked!! Fight :)

Show 4 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.