Get elements by class / id with pure JavaScript

6

In jQuery, we use quotation marks to get $('div.oi') . And in pure JavaScript? Piss if we use without quotes is different.

If we change the css for example: With jQuery:

$('teste').css(teste);
    
asked by anonymous 05.06.2017 / 19:56

1 answer

10

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 to both the document and a specific element (to get descendants of it).

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

References

05.06.2017 / 19:58