Blog>
Snippets

Query Selector Modification

Use `querySelector` to select the first instance of a `.special` class, and add a new CSS class to it.
// Use querySelector to find the first element with class 'special'
var element = document.querySelector('.special');

// Add a new class 'new-class' to the selected element
if (element) element.classList.add('new-class');
This code selects the first HTML element with the class 'special' and adds the 'new-class' CSS class to it. It first checks if the element exists to avoid any errors.