DEV Community

Mainasara Al-amin Tsowa
Mainasara Al-amin Tsowa

Posted on

Using CSS Selectors In Javascript

In CSS, selectors are patterns used to select the element(s) you want to style, but as you can tell from the title above, selectors are also useful in javascript and below are some examples on how to use them.

Basics

Using a selector in javascript

  • Use the .querySelector method
const div = document.querySelector("div") // => First occurence of a div element in the document

const p = div.querySelector("p") // => First occurence of a p element in the div

Enter fullscreen mode Exit fullscreen mode
  • To get all matching elements, use the document.querySelectorAll method
document.querySelectorAll("div") // NodeList of all div elements
Enter fullscreen mode Exit fullscreen mode

By IDs

To get an element by its ID, use a # before the element ID

document.querySelector("#id") // => document.getElementById('id')
Enter fullscreen mode Exit fullscreen mode

By classes

To get elements by class, use a . before the class name

document.querySelectorAll(".myElementClass")
Enter fullscreen mode Exit fullscreen mode

By tag name

To get elements by tag name, just input the tag name

document.querySelectorAll("body") // => document.getElementsByTagName('body')
Enter fullscreen mode Exit fullscreen mode

Replicating .getElementById and getElementsByTagName

  • Replicating .getElementById
document.querySelector("#myDivId") // => document.getElementById('myDivId')
Enter fullscreen mode Exit fullscreen mode
  • Replicating .getElementsByTagName
document.querySelectorAll("a") // => document.getElementsByTagName('a')
Enter fullscreen mode Exit fullscreen mode

All elements

To get all elements use *

document.querySelectorAll("*") // => NodeList[...]
Enter fullscreen mode Exit fullscreen mode

Using multiple selectors

To use multiple selectors, we seperate each of them with a ,.

<html>
    <body>
        <p>Hello i am a paragraph</p>
        <a href="https://awesomeplace.com">Hey I am a link</a>
        <a href="https://anotherplace.com">I am another link</a>
    </body>
</html>
Enter fullscreen mode Exit fullscreen mode
document.querySelectorAll("p, a") // => NodeList[p,a,a]
Enter fullscreen mode Exit fullscreen mode

More with elements

In the above examples, we made basic queries, but other things can be done like getting elements by order or parent.

Getting element children

There are two variants of this, one gets an element's child no matter how deep it is down the tree, and the other gets an element's direct child.

<html>
    <body>
        <p>Hello i am a paragraph</p>
        <div>
            <a href="https://awesomeplace.com">Hey I am a link</a>
            <p>
                Hello i am a paragraph and here's
                <a href="https://anotherplace.com">a link</a>
            </p>
        </div>
    </body>
</html>
Enter fullscreen mode Exit fullscreen mode

With the above HTML as an example, we will look at these two variants.

  • Direct child
document.querySelector("div > a") // => <a href="https://awesomeplace.com">Hey I am a link</a>
Enter fullscreen mode Exit fullscreen mode
  • All children
document.querySelectorAll("div a") // => NodeList[a,a]
Enter fullscreen mode Exit fullscreen mode

Getting elements by order

There are two ways to do this also. Consider the following HTML.

<html>
    <body>
        <div>
            <a href="https://awesomeplace.com">Hey I am a link</a>
            <pre>I should intervene but i wont</pre>
            <p>Hello i am another paragraph</p>
        </div>
        <p>Hello i am a paragraph</p>
    </body>
</html>
Enter fullscreen mode Exit fullscreen mode
  • Placed after
document.querySelector("div + p") // => <p>Hello i am a paragraph</p>
Enter fullscreen mode Exit fullscreen mode
  • Preceded by

With ~, it does not matter the element immediately behind matches.

document.querySelector("a ~ p") // => <p>Hello i am another paragraph</p>
Enter fullscreen mode Exit fullscreen mode

and we can see that the pre element did not affect the result because it does not matter if the pre was there in the first place. But the following selector will fail because it checks the element immediately above it.

document.querySelector("a + p") // => null
Enter fullscreen mode Exit fullscreen mode

Getting elements by attribute

An attribute selector starts with [ and ends with ] and is used as such

<html>
    <body>
        <p style="color:blue;">Hello i am styled</p>
        <p>Hello i have no style</p>
    </body>
</html>
Enter fullscreen mode Exit fullscreen mode
document.querySelector("p[style]") // => <p style="color:blue;">Hello i am styled</p>
Enter fullscreen mode Exit fullscreen mode

Check attribute value

To check an attribute value we use the = symbol.

<html>
    <body>
        <a href="https://awesomeplace.com">Hey I am a link</a>
        <a href="https://anotherplace.com">I am another link</a>
    </body>
</html>
Enter fullscreen mode Exit fullscreen mode
document.querySelector('a[href="https://awesomeplace.com"]') // => <a href="https://awesomeplace.com">Hey I am a link</a>
Enter fullscreen mode Exit fullscreen mode

More with attribute values

  • Check if attribute starts with...
document.querySelector('a[href^="https://awesome"]') // => <a href="https://awesomeplace.com">Hey I am a link</a>
Enter fullscreen mode Exit fullscreen mode
  • Check if attribute ends with...
document.querySelectorAll('a[href$=".com"]') // => NodeList[a,a]
Enter fullscreen mode Exit fullscreen mode
  • Check if the attribute contains a substring
document.querySelectorAll('a[href*="place"]') // => NodeList[a,a]
Enter fullscreen mode Exit fullscreen mode

Advanced selectors

  • :focus

This selects the element that currently has focus

  • :visited

This is used with a tags and selects links that have been visited

  • :link

This is also used with a tags but in this case, selects links that have not been visited

  • :enabled

This selects elements that are enabled(not disabled)

<html>
    <body>
        <p>I am a paragraph</p>
        <p>I am another paragraph</p>
        <a href="https://awesomeplace.com">Hey I am a link</a>
        <a href="https://anotherplace.com">I am another link</a>
        <button disabled="true"> I have been disabled </button>
    </body>
</html>
Enter fullscreen mode Exit fullscreen mode
document.querySelectorAll(":enabled") // => NodeList[p,p,a,a]
Enter fullscreen mode Exit fullscreen mode
  • :disabled

This selects elements that have been disabled

<html>
    <body>
        <p>I am a paragraph</p>
        <p>I am another paragraph</p>
        <a href="https://awesomeplace.com">Hey I am a link</a>
        <a href="https://anotherplace.com">I am another link</a>
        <button disabled="true"> I have been disabled </button>
    </body>
</html>
Enter fullscreen mode Exit fullscreen mode
document.querySelector(":disabled") // => <button disabled="true"> I have been disabled </button>
Enter fullscreen mode Exit fullscreen mode
  • :first-child

This selects the element that is the first child of its parent

<html>
    <body>
        <p>I am a paragraph</p>
        <p>I am another paragraph</p>
        <a href="https://awesomeplace.com">Hey I am a link</a>
        <a href="https://anotherplace.com">I am another link</a>
    </body>
</html>
Enter fullscreen mode Exit fullscreen mode
document.querySelector("p:first-child") // => <p>I am a paragraph</p>
Enter fullscreen mode Exit fullscreen mode
  • :last-child

This selects the element that is the last child of its parent

<html>
    <body>
        <p>I am a paragraph</p>
        <p>I am another paragraph</p>
        <a href="https://awesomeplace.com">Hey I am a link</a>
        <a href="https://anotherplace.com">I am another link</a>
    </body>
</html>
Enter fullscreen mode Exit fullscreen mode
document.querySelector("p:last-child") // => <a href="anotherplace.com">I am another link</a>
Enter fullscreen mode Exit fullscreen mode
  • el:first-of-type

This selects the element that is the first child of its parent and is the same type as el

<html>
    <body>
        <p>I am a paragraph</p>
        <a href="https://awesomeplace.com">Hey I am a link</a>
        <p>I am another paragraph</p>
        <a href="https://anotherplace.com">I am another link</a>
    </body>
</html>
Enter fullscreen mode Exit fullscreen mode
document.querySelector("a:first-of-type") // => <a href="https://awesomeplace.com">Hey I am a link</a>
Enter fullscreen mode Exit fullscreen mode
  • el:last-of-type

This selects the element that is the last child of its parent and is the same type as el

<html>
    <body>
        <p>I am a paragraph</p>
        <a href="https://awesomeplace.com">Hey I am a link</a>
        <p>I am another paragraph</p>
        <a href="https://anotherplace.com">I am another link</a>
    </body>
</html>
Enter fullscreen mode Exit fullscreen mode
document.querySelector("p:last-of-type") // => <p>I am another paragraph</p>
Enter fullscreen mode Exit fullscreen mode
  • :not(selector)

This selects elements that don't match the selector

<html>
    <body>
        <p>I am a paragraph</p>
        <a href="https://awesomeplace.com">Hey I am a link</a>
        <a href="https://anotherplace.com">I am another link</a>
    </body>
</html>
Enter fullscreen mode Exit fullscreen mode
document.querySelector(":not(a)") // => <p>I am a paragraph</p>
Enter fullscreen mode Exit fullscreen mode
  • :nth-child(n)

This selects the element that is the n th child of its parent.

<html>
    <body>
        <div>
            <p>I am a paragraph</p>
            <a href="https://awesomeplace.com">Hey I am a link</a>
            <a href="https://anotherplace.com">I am another link</a>
        </div>
    </body>
</html>
Enter fullscreen mode Exit fullscreen mode
document.querySelector("div:nth-child(2)") // => <a href="https://awesomeplace.com">Hey I am a link</a>
Enter fullscreen mode Exit fullscreen mode
  • :nth-last-child(n)

This selects the element that is the n th to the last child of its parent.

<html>
    <body>
        <div>
            <p>I am a paragraph</p>
            <a href="https://awesomeplace.com">Hey I am a link</a>
            <a href="https://anotherplace.com">I am another link</a>
        </div>
    </body>
</html>
Enter fullscreen mode Exit fullscreen mode
document.querySelector("div:nth-last-child(1)") // => <a href="https://anotherplace.com">I am another link</a>
Enter fullscreen mode Exit fullscreen mode

Mix and match

These selectors can be mixed together to perform some complex checks. e.g

  • A disabled button of class 'btn'
<html>
    <body>
        <div>
            <p>I am a paragraph</p>
            <a href="https://awesomeplace.com">Hey I am a link</a>
            <a href="https://anotherplace.com">I am another link</a>
        </div>
        <button disabled="true">I am disabled</button>
        <button disabled="true" class="btn">I am also disabled</button>
    </body>
</html>
Enter fullscreen mode Exit fullscreen mode
document.querySelector('button.btn:disabled') // => <button disabled="true" class="btn">I am also disabled</button>
Enter fullscreen mode Exit fullscreen mode
  • All disabled buttons in a form
<html>
    <body>
        <form method="POST">
            <input type="text" name="firstname" placeholder="firstname"/>
            <input type="text" name="lastname" placeholder="lastname"/>
            <button disabled="true">Clear inputs</button>
            <button type="submit">Submit</button>
        </form>
        <button disabled="true">I am disabled</button>
        <button disabled="true" class="btn">I am also disabled</button>
    </body>
</html>
Enter fullscreen mode Exit fullscreen mode
document.querySelector('form > button:disabled') // => <button disabled="true">Clear inputs</button>
Enter fullscreen mode Exit fullscreen mode
  • All disabled buttons in a form and all buttons outside it
<html>
    <body>
        <form method="POST">
            <input type="text" name="firstname" placeholder="firstname"/>
            <input type="text" name="lastname" placeholder="lastname"/>
            <button disabled="true">Clear inputs</button>
            <button type="submit">Submit</button>
        </form>
        <button>I am not disabled</button>
        <button class="btn">I am also not disabled</button>
    </body>
</html>
Enter fullscreen mode Exit fullscreen mode
document.querySelectorAll('form > button:disabled, form ~ button') // => NodeList[button, button, button]
Enter fullscreen mode Exit fullscreen mode
  • All links to external pages
<html>
    <body>
        <div>
            <p>I am a paragraph</p>
            <a href="https://awesomeplace.com">Hey I am a link</a>
            <a href="https://anotherplace.com">I am another link</a>
        </div>
        <a href="/otherpage.html">I will to the other pages</a>
    </body>
</html>
Enter fullscreen mode Exit fullscreen mode
document.querySelectorAll('a[href^="https://"]') // => NodeList[a,a]
Enter fullscreen mode Exit fullscreen mode

And to get links that are not to external pages, use

document.querySelector('a:not([href^="https://"])') // => <a href="/otherpage.html">I will to the other pages</a>
Enter fullscreen mode Exit fullscreen mode

Conclusion

These are just some of the ways you can use selectors in javascript and if you want to know more, here is a link to a CSS selector reference on w3c.

Thanks for reading!!!

Top comments (5)

Collapse
 
pra3t0r5 profile image
Pra3t0r5

Awesome! I'm using jQuery and several friends told me I should try with pure JavaScript. Looks like the transition will be pretty easy!

Collapse
 
ihilt profile image
Ian Hilt

This website is helpful if you don't want to use jQuery or want to learn plain javascript.

youmightnotneedjquery.com/

Collapse
 
neutrino2211 profile image
Mainasara Al-amin Tsowa

Yeah, since I learned this I haven't been heavily reliant on jQuery 😁

Collapse
 
jackedwardlyons profile image
Jack Lyons

Awesome post. It goes well with this article "The 30 CSS Selectors You Must Memorize"

code.tutsplus.com/tutorials/the-30...

Collapse
 
ufukcam profile image
Ufuk 💻🚀

Thank you so much. Now I understood better which I didn’t understand parts. 🙏🏻👏