Native Javascript element selector best practice

twitter logo ・1 min read

Hey all,

So coming from Jquery, I was always told the best method to select an element is to give it a class name and use the $(".someElementClass") method.

However now not using Jquery in my Vue project, what is the best practice for selecting elements.

I am currently giving elements ID's and using the document.getElementById("someElementID");

Very curious to see what peoples opinions are!

twitter logo DISCUSS (5)
markdown guide
 

you can use the native methods document.querySelector and document.querySelectorAll that respectively return the first or all the elements that match the CSS query selector you provide. It works almost identically to jQuery (there are some limitations when using pseudo-selectors though).

developer.mozilla.org/en-US/docs/W...

const el = document.querySelector('.someElementClass');

As they are Element methods, they can be used not only on document but on any Element to find their children

const parent = document.querySelector('.parent');
const children = parent.querySelectorAll('.children');

Some people even declare some shortcuts to access these methods quickly:

window.$ = document.querySelector;
window.$$ = document.querySelectorAll;

const header = $('h1');
const headersList = $$('h1');
 

Hi Ross, you can use document.getElementsByClassName() but the real question is, why are you accessing the DOM directly if you're using Vue?

You shouldn't need it usually, but maybe you're... porting an app?

ps. #ama is a tag for people that are supposed to hold Ask me anything, a form of public forum in which a person with a particular walk of life answers questions by people. I would change your tags to #help #vue #javascript for example

 

This. 99.9% you shouldn't touch the DOM manually, Vue being data driven is how you should always approach your app. Set the values in data and initialise the plugin with that data.

That said, if you do need to access an element, the simplest "Vue way" to do it is by using $refs

 

doh sorry,

I am accessing the dom to bind dates to date picker, and preselected values for lists

 

Wait a second you sparked something there for me thank you

Classic DEV Post from Jan 31

What are the least intuitive fundamentals and best practices in software development?

Some things we do kind of make sense in and of themself. Some things have evolv...

Ross Summerell profile image

Sore eyes?

dev.to now has dark mode.

Go to the "misc" section of your settings and select night theme ❤️