Javascript querySelector for Elem with Multiple Classes

Javascript Code to Get Handle to Elem that Has Multiple Classes and How to use Wildcards for Classes that Contain Multiple Values

Home Short:

Lets say you want to use querySelector() to get handle to an element that has multiple classes, for example.

The basic syntax for this is to use document.querySelector('[class*="somevalue"]'), chaining [class*="somevalue"] as many times as you wish to get more specific. somevalue will be any part of the class list.

All of the following examples will correctly get a handle to the div in the textarea above:

The value of this is that sometimes an elements classlist can change based upon certain conditions. Simply use the querySelector() wildcard using values that you know won't change.

Another example of the potential value of this is lets say you have 3 different elements contained within a div. Lets say 3 textareas for example. And lets say the classes of each of these 3 textareas is class="visitoranswer1 confirm", class="visitoranswer2 confirm", class="visitoranswer3 confirm".

Well what happens if you need to be able to get the parent div of one of these textareas but you dont know which textarea it will be at the time. By simply using ...

This way you can always reliably get a hold of the parent element no matter which of the textareas is currently if focus within the coding environment.

The whole basis of Javascript querySelector for Elem with Multiple Classes is to focus on what is stable and reliable and be able to get a hold of it, even if and when specific values of classLists might change.

S
H
A
R
E