Get elements by class/id with pure JavaScript

Question:

In jQuery, we use quotes to get $('div.oi') . What about pure JavaScript? Piss if we use no quotes is different.

If we are going to change the css for example: With jQuery:

$('teste').css(teste);

Answer:

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');

Both querySelector and querySelectorAll can be applied either to the document or to a specific element (to get descendants of it).

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

References

Scroll to Top