Take elements by class/id with pure Javascript

Asked

Viewed 6,117 times

6

In jQuery, we use quotes to pick up $('div.oi'). What about pure Javascript? Piss if we use without quotation marks is different.

If we change the css for example: With jQuery:

$('teste').css(teste);
  • I think this question has been asked before here on the net

  • Would you have the link, Marcelo? I’m sorry, I didn’t think.

  • 1

    It’s one thing to get id, another thing to class, id is a single element on a page, whereas class can have as many elements as needed

1 answer

11


The modern way in pure JS is:

// Para um elemento, por seletor
var el = document.querySelector('div.oi');

// Para múltiplos elementos
var els = document.querySelectorAll('div.oi');

// Para um elemento por ID, da maneira tradicional:
var el = document.getElementById('id_aqui');

So much querySelector how much querySelectorAll can be applied to both Document and a specific element (to catch descendants of it).

There are also other methods, such as getElementsByClassName, that need to be used in older browsers.

References

  • In this case, in Jquery you can take id and class with $(' '), already in pure Javascript is different. Right?

  • I didn’t really understand the difference between querySelector and querySelectorAll. I know All is all, but what do you mean? When I use the querySelector will only get 1? How so 1?

  • 2

    @Lucascarvalh querySelectorAll will return an array with the elements, while querySelector returns a single element.

  • @Lucascarvalho Com querySelector/querySelectorAll you can search by selector as in jQuery (but jQuery accepts more selectors). Therefore, you can search by id with querySelector as well, as in var el = document.querySelector('#meuId'). About the difference between the two methods, this is what Marconi explained.

Browser other questions tagged

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