DOM Manipulation
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.Show and Hide Elements
JavaScript allows you to change the CSS properties of an element by accessing itsstyle property. This way, you can show or hide HTML elements by changing their display property.
Hide Elements
In order to hide an HTML element, you can use thedisplay: none CSS property. This will remove the element from the page layout, but it will still be present in the DOM.
Show Elements
Most HTML elements have a defaultdisplay 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 ('').
Rendering DOM Elements
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.Representing a DOM Tree
Each element is an object with atype property representing the element’s tag name, and a props object containing the element’s attributes, event listeners, and children.
type property, only containing a props object with a nodeValue property.
Render Function
Creating Elements
createElement
createTextNode
Modifying Elements
Text Content
Attributes
Classes
Styles
Removing Elements
Inserting Elements
appendChild
insertBefore
insertAdjacentHTML
Cloning Elements
Best Practices
Minimize DOM manipulation
Minimize DOM manipulation
DOM manipulation is expensive. Batch changes together and use DocumentFragment for multiple insertions.
Use classList over className
Use classList over className
classList provides methods like add, remove, toggle, and contains, making it easier and more reliable than manipulating className string.Sanitize user input
Sanitize user input
When using
innerHTML with user input, always sanitize the content to prevent XSS attacks. Consider using textContent instead.Cache DOM references
Cache DOM references
If you need to access an element multiple times, cache the reference instead of querying the DOM repeatedly.