JavaScript & The DOM
The Document Object Model (DOM) is an application programming interface (API) for valid HTML and well-formed XML documents. It defines the logical structure of documents and the way a document is accessed and manipulated.
Selecting Elements
To modify an element, you must first find it in the DOM tree. The document.getElementById('id') method is the fastest and most specific way to select a single node. If you need more complex targeting, like selecting by class or attribute, document.querySelector('.class') allows you to pass any valid CSS selector string. To grab multiple elements, use document.querySelectorAll('div'), which returns a NodeList you can iterate over using a forEach loop.
Modifying Content
Once selected, the properties innerHTML and textContent let you change what's inside. Use innerHTML only when you intend to render stringified HTML tags (like injecting a new <strong> tag). Beware of XSS vulnerabilities if this input comes from a user. For pure text changes, always default to textContent for performance and security.
Modifying Attributes
JavaScript can read and modify element attributes on the fly using methods like setAttribute('href', 'newLink.com') and getAttribute('id'). Many common attributes also have direct property accessors on the DOM node, such as element.id or element.className.
Security Note: XSS Attacks+
Cross-Site Scripting (XSS) occurs when malicious scripts are injected into otherwise benign and trusted websites. If you take user input and place it directly into your HTML via innerHTML, a hacker could input a <script> tag that steals user session cookies. Always sanitize user input or prefer textContent, which safely escapes any HTML characters.
