The Document Object Model (DOM) is the browser’s representation of your HTML. JavaScript provides powerful APIs to manipulate the DOM and create dynamic, interactive web pages.
JavaScript allows you to change the CSS properties of an element by accessing its style property. This way, you can show or hide HTML elements by changing their display property.
In order to hide an HTML element, you can use the display: none CSS property. This will remove the element from the page layout, but it will still be present in the DOM.
const hide = (...el) => [...el].forEach(e => (e.style.display = 'none'));hide(...document.querySelectorAll('img'));// Hides all <img> elements on the page
Most HTML elements have a default display property value. For example, the default value for <div> elements is block, while the default value for <span> elements is inline. In order to show an element, you can set its display property to its default value, or to an empty string ('').
const show = (...el) => [...el].forEach(e => (e.style.display = ''));show(...document.querySelectorAll('img'));// Shows all <img> elements on the page
Combining the spread operator (...) with Array.prototype.forEach() allows you to show or hide multiple elements at once.
Have you ever wondered how React’s rendering works under the hood? Here’s a simple JavaScript function that renders a DOM tree in a specified container.
Each element is an object with a type property representing the element’s tag name, and a props object containing the element’s attributes, event listeners, and children.
const element = document.getElementById('my-element');// Get attributeconst value = element.getAttribute('data-id');// Set attributeelement.setAttribute('data-id', '123');// Remove attributeelement.removeAttribute('data-id');// Check if attribute existsif (element.hasAttribute('data-id')) { console.log('Has data-id attribute');}
const element = document.getElementById('my-element');// Add classelement.classList.add('active');// Remove classelement.classList.remove('inactive');// Toggle classelement.classList.toggle('highlighted');// Check if has classif (element.classList.contains('active')) { console.log('Element is active');}
const element = document.getElementById('my-element');// Before the element itselfelement.insertAdjacentHTML('beforebegin', '<p>Before</p>');// Just inside the element, before its first childelement.insertAdjacentHTML('afterbegin', '<p>First child</p>');// Just inside the element, after its last childelement.insertAdjacentHTML('beforeend', '<p>Last child</p>');// After the element itselfelement.insertAdjacentHTML('afterend', '<p>After</p>');