Engineering note · Javascript

Apply Styles to Multiple Elements

By Published Updated

Javascript

Apply a style to multiple elements at once by adding a class. Here highlighting selected list items with a single class addition:

Html :

CODE SAMPLE Code snippet
<button id="highlightButton">Highlight Items</button>
<ul id="itemList">
    <li>Item 1</li>
    <li>Item 2</li>
    <li>Item 3</li>
</ul>

Javascript:

CODE SAMPLE Code snippet
<script>
    document.getElementById('highlightButton').addEventListener('click', () => {
        const items = document.querySelectorAll('#itemList li');
        items.forEach(item => {
            item.classList.add('highlight');
        });
    });
</script>

More engineering notes

Efficiently Append Multiple Elements

Appending multiple elements to the DOM can be inefficient if done individually. Use a document frag...

Dynamically Update Attribute Values

To change the attributes of multiple elements based on user input or other dynamic conditions. Use ~...