Selectors in JavaScript
Many times we use jQuery for ease of selecting DOM elements and being able to work with them. But, we can access the same elements in similar ways with pure JavaScript; using the Selectors getElementById, getElementsByTagNames and getElementsByClassName in addition to the very little known querySelector and querySelectorAll.
What is it for and how to use querySelector?
If we have worked with selectors in CSS; then it will be very easy for us to work with this JavaScript selector, since it allows us to obtain the elements using the same syntax that we apply when we create our rules in CSS; with querySelector we can obtain the first DOM element that matches what we pass to it. It works exactly the same as jQuery selectors.
Example of using the querySelector
<ul id="ejemplo1">
<li class="uno" id="uno"> uno </li>
<li class="dos" id="dos"> dos </li>
<li class="tres" id="tres"> tres </li>
<li class="cuatro" id="cuatro"> cuatro </li>
</ul>
document.querySelector('#ejemplo1 li');
// get <li class="uno" id="uno"> uno </li>
document.querySelector('#ejemplo1 .uno');
// get <li class="uno" id="uno" > uno </li>
document.querySelector('#ejemplo1 #dos.dos');
// get <li class="dos" id="dos" > dos </li>
document.querySelector('#ejemplo1 > #dos.dos');
// get <li class="dos" id="dos" > dos </li>What is it for and how to use querySelectorAll?
querySelectorAll works in the same way as the previous selector (querySelector), but returns all the elements that match the given condition, instead of just the first element; this collection of elements will be represented in an array.
Example of using querySelectorAll
<ul id="ejemplo2">
<li class="uno" id="uno" > uno </li>
<li class="dos" id="dos" > dos </li>
<li class="tres" id="tres" > tres </li>
<li class="cuatro" id="cuatro" > cuatro </li>
</ul>
document.querySelectorAll('#ejemplo2 li');
/*
It brings us an array with the elements that meet the previous condition
[
<li class="uno" id="uno"> uno </li>,
<li class="dos" id="dos"> dos </li>,
<li class="tres" id="tres"> tres </li>,
<li class="cuatro" id="cuatro"> cuatro </li>
]
*/What is it for and how to use GetElementById?
This method allows us to obtain a DOM element according to the value of its id attribute:
document.getElementById(<id_elemento>)GetElementById Usage Example
For the next element:
<div id='div_id' > div con id='div_id' </div> We could obtain it in the following way:
document.getElementsById("div_id")What is it for and how to use getElementsByTagName?
This method allows us to obtain all DOM elements according to the name of the element tag; the collection of elements will be returned in an array.
document.getElementsByTagName(<nombre_etiqueta_elemento>)GetElementsByTagName Usage Example
For the next element:
<p> etiqueta p 1 </p>
<h2> etiqueta h2 </h2>
<p> etiqueta p 2 </p> We could obtain it in the following way:
document.getElementsByTagName("p")
/*
It brings us an array whose tag name is p
[
<p> etiqueta p 1 </p>,
<p> etiqueta p 2 </p>
]
*/What is it for and how to use getElementsByClassName?
This method allows us to obtain all the elements of the DOM according to the value of its class attribute; This collection will be returned in an array.
document.getElementById(<class_elemento>)GetElementsByClassName Usage Example
<p class='miclase' > p con class='miclase' </p>
<h1 class='miclase' > h1 con class='miclase' </h1>
<p class='otraclase' > p con class='otraclase' </p>
<p class='miclase' > p con class='miclase' </p>
<p class='miclase' > p con class='miclase' </p>
document.getElementsByClassName("miclase")
/*
It brings us an array with the elements whose class is 'myclass'
[
<p class='miclase' >p con class='miclase' </p>,
<h1 class='miclase' >h1 con class='miclase' </h1>>,
<p class='miclase' >p con class='miclase' </p>,
<p class='miclase' >p con class='miclase'</p>
]
*/Conclusion
As we can see; we have many different ways to easily access DOM elements; without using any framework like jQuery and the repercussions that this would bring us.
Note: The id attribute must be unique on each HTML page.
4+1 essential CSS selectors when programming
In this post I will show you the main selectors used by me when creating a Cascading Style Sheet, in one way or another they have become essential or essential in its creation.
Did you know...? With selectors we can save a lot of work and thus avoid "inventing" names through classes or identifiers to reference or select elements.
4+1. A[href*="github.com"]
Este selector es muy útil cuando queremos aplicar diferentes estilos según la URL que referencia el enlace; por ejemplo, si quisiéramos agregar algún detalle extra como un icono al principio del enlace:
a[href*="github.com"]:before {
content:url("github-logo.png")
}
a[href*="google.com"]:before {
content:url("google.png")
}And with a little more CSS we can get something like the following:
4. A > B
This other selector known as the child selector is very useful when we want to apply different styles to different children or levels; It is widely used when creating multilevel menus like the following:
For example, if we wanted to apply a style only to the li lists within the innermost ul whose main characteristic is the red background:
ul > li > ul {
padding:10px;
background:#F00;
}Now part of the outermost ul style definition:
ul{
background:#CCC;
}Remaining as follows our example:
3. A:visited
Returning with the links, you will notice every time you visit a web page, for example in Google, they have a different color:

This selector allows you to obtain those links that have been visited and change the style; for example the color of the text:
a:visited { color: #609; }A, B, C
This selector allows you to save many lines and redundancy of CSS code by allowing you to chain selectors and inherit the style that you have in common:
h1, h2, h3 {
color: #FF0000;
font-family: Arial;
}To apply the rest of the styles to the different selectors:
h1 { font-size: 2em; }
h2 { font-size: 1.5em; }
h3 { font-size: 1.2em; }1. A:nth-child(N)
Here we have an incredible selector which allows you to select elements in order; for example, if we have the following HTML code:
<ul>
<li>Primero</li>
<li>Segundo</li>
<li>Tercero</li>
<li>Cuarto</li>
<li>Quinto</li>
<li>Sexto</li>
<li>Séptimo</li>
</ul>It is very useful when we want to apply different styles to the cells or rows of tables, lists, etc.; It also allows you to use formulas like 2n+1 to obtain certain elements that follow a pattern; more information at: The nth-child pseudo-class in CSS.
ul.nth_numerica li:nth-child(1),
ul.nth_numerica li:nth-child(3) {
background: #999;
}Conclusions
In this post we have seen some of the many selectors that exist in CSS that I consider to be the most important or essential in order of relevance or importance, but of course there are many more that can be useful depending on the objective to be achieved.
CSS and JavaScript :has Selector - Conditional Pseudoclass

Content Index
- What is it for and how to use querySelector?
- Example of using the querySelector
- What is it for and how to use querySelectorAll?
- Example of using querySelectorAll
- What is it for and how to use GetElementById?
- GetElementById Usage Example
- What is it for and how to use getElementsByTagName?
- GetElementsByTagName Usage Example
- What is it for and how to use getElementsByClassName?
- GetElementsByClassName Usage Example
- Conclusion
- 4+1 essential CSS selectors when programming
- 4+1. A[href*="github.com"]
- 4. A > B
- 3. A:visited
- A, B, C
- 1. A:nth-child(N)
- Conclusions
- CSS and JavaScript :has Selector - Conditional Pseudoclass
- ️ The Problem with Image and Text Formatting
- The problem of being able to select a consecutive HTML element
- How the :has() Selector Works
- The Traditional Selector
- The Selector Solution with :has()
- Final Implementation
I'm going to show you an implementation of the CSS :has() selector and how it allowed me to solve a small design problem I had. The advantage of this relatively new selector is its ability to simplify complex queries.
️ The Problem with Image and Text Formatting
This content is from the book viewer of my Academia application. The book's text was imported to the web as clean HTML, inherited from Google Docs, which resulted in a very specific image and caption structure:
<p><span><img src="..." alt="" width="..." height="..." title=""></span></p> <p><span>Figura 1-1: Ventana de Laravel Herd en MacOS</span></p>My goal: To make the paragraph containing the "Figura 1-1: Ventana de Laravel Herd en MacOS" (the caption) centered.
The problem of being able to select a consecutive HTML element
In the HTML, the image is inside a paragraph (<p>) and the caption is in the following paragraph. The problem is that the caption doesn't have any class that distinguishes it from any other normal paragraph in the text, and CSS doesn't have a native selector that allows me to select an element based on what its preceding sibling contains.
What I need: Select the paragraph that is the immediate sibling of the paragraph that contains an image.
How the :has() Selector Works
The :has() selector is like a conditional. It allows you to select an element (the parent or container) based on whether or not it contains (the child) a specific selector.
The Traditional Selector
If we used the traditional syntax to select the image, the query would return the most specific element, which is the image itself:
document.querySelector(".post p img") // Returns the <img> element:<p><span><img src="/images/example/libros/laravel/image24.png" alt="" width="247" height="410" title=""></span></p>This is a problem, since the image is not a sibling of the caption. Its parent (the paragraph) is, but we can't select the parent and then select the child again.
The Selector Solution with :has()
This is where the :has() selector comes in. Instead of returning the <img> element, we ask it to return the paragraph (<p>) that contains the image (<img>). The :has(img) acts as a condition:
// Returns the <p> element that contains the <img>
document.querySelector(".post p:has(img)") <p><span><img src="/images/example/libros/laravel/image24.png" alt="" width="247" height="410" title=""></span></p>With this, our selection reference becomes the image's paragraph, which is the sibling of the caption's paragraph.
Final Implementation
By being able to select the paragraph that contains the image (the preceding sibling), we can now use the adjacent sibling selector (+) to target the caption's paragraph.
The adjacent sibling selector (+) selects an element that is placed immediately after a specific element, provided both have the same parent.
// Returns the <p> that is immediately after the <p> that has an <img>
document.querySelector(".post p:has(img) + p") The CSS Style
Finally, in CSS, the solution to center the caption is as follows:
<style>
.post p:has(img) + p {
text-align: center;
}
</style>This implementation allows us to center that specific paragraph without having to add classes in the HTML or modify the inherited structure of the book. It's a perfect demonstration of how :has() allows for much more elaborate queries and solves problems that were previously impossible with native CSS alone.
I agree to receive announcements of interest about this Blog.
Learn how to use the conditional pseudo-class :has() in CSS and JavaScript. Solve design problems, such as centering a caption, by selecting elements based on their adjacent siblings.