How to Escape Colons in CSS Classes in JavaScript
When selecting an HTML element with a CSS class containing special characters such as colons (:) using document.querySelector
or document.querySelectorAll
, you need to escape those characters to ensure proper selection. For example, if the CSS class is empty:hidden
, which contains a colon, write the selector as follows:
const elements = document.querySelectorAll('.empty\\:hidden');
In this code, the backslash (\
) is used to escape the colon in the CSS class name. This allows you to correctly target elements with the empty:hidden
class. Here's a complete example of how you can use this code to select and manipulate elements with colons in class names:
<!DOCTYPE html>
<html>
<head>
<style>
.empty\:hidden {
display: none;
}
</style>
</head>
<body>
<div class=`empty:hidden`>This is a hidden element with the class `empty:hidden`.</div>
<div>This is a visible element.</div>
<script>
const elements = document.querySelectorAll('.empty\\:hidden');
elements.forEach(element => {
element.textContent = "This element was selected and manipulated.";
});
</script>
</body>
</html>
In this example, the JavaScript code selects all elements with the empty:hidden
class and changes their content. The backslash before the colon is used to correctly escape the colon character in the CSS class name.
Featured Merch
Latest Posts
- Open Applications in Fullscreen on Ubuntu
- Manage Long-Running Tasks with Screen on a Remote Linux Server
- Troubleshooting External Hard Drives on Linux
- How to Prevent SSH Timeout on Linux Systems
- Getting Started with Print-on-Demand Merchandise
Featured Book
Subscribe to RSS Feed
This post was written by Ramiro Gómez (@yaph) and published on . Subscribe to the Geeksta RSS feed to be informed about new posts.
Tags: code howto javascript web development
Disclosure: External links on this website may contain affiliate IDs, which means that I earn a commission if you make a purchase using these links. This allows me to offer hopefully valuable content for free while keeping this website sustainable. For more information, please see the disclosure section on the about page.
Share post: Facebook LinkedIn Reddit Twitter