JS HTML Objects

In JavaScript, the term “HTML Objects” refers to the JavaScript objects that represent HTML elements. When a web page is loaded, the browser creates a Document Object Model (DOM), which is a tree-like representation of the HTML structure. Each node in this DOM tree is a JavaScript object, and these objects have properties and methods that allow you to interact with and manipulate the corresponding HTML elements.

Essentially, an HTML object is a programmatic interface to an HTML element.

How HTML Elements Become JavaScript Objects

When your browser parses HTML:

HTML

<!DOCTYPE html>
<html>
<head>
    <title>HTML Objects</title>
</head>
<body>
    <h1 id="pageTitle">My Awesome Page</h1>
    <p class="content">This is a paragraph.</p>
    <button>Click Me</button>
</body>
</html>

The browser creates a series of JavaScript objects:

  • The <html> tag becomes an HTMLHtmlElement object.
  • The <head> tag becomes an HTMLHeadElement object.
  • The <title> tag becomes an HTMLTitleElement object.
  • The <body> tag becomes an HTMLBodyElement object.
  • The <h1> tag becomes an HTMLHeadingElement object.
  • The <p> tag becomes an HTMLParagraphElement object.
  • The <button> tag becomes an HTMLButtonElement object.
  • Even text content within tags becomes Text objects.

All of these are derived from a common base HTMLElement interface, which itself inherits from Element, Node, and ultimately EventTarget and Object. This inheritance chain is what gives all HTML objects common properties and methods (like id, className, style, addEventListener, etc.) and also specialized ones (like value for inputs, href for anchors).

Accessing HTML Objects (Selecting Elements)

To work with an HTML object in JavaScript, you first need to get a reference to it. This is typically done using DOM selection methods available on the document object:

  1. document.getElementById('idName'):
    • Returns the unique HTMLElement object corresponding to the id.
    • Example:JavaScriptconst titleElement = document.getElementById('pageTitle'); console.log(titleElement); // Logs the HTMLHeadingElement object
  2. document.getElementsByClassName('className'):
    • Returns a live HTMLCollection of HTMLElement objects with the specified class.
    • Example:JavaScriptconst contentParagraphs = document.getElementsByClassName('content'); console.log(contentParagraphs[0]); // Logs the first HTMLParagraphElement object
  3. document.getElementsByTagName('tagName'):
    • Returns a live HTMLCollection of HTMLElement objects with the specified tag name.
    • Example:JavaScriptconst allButtons = document.getElementsByTagName('button'); console.log(allButtons[0]); // Logs the HTMLButtonElement object
  4. document.querySelector('CSS-selector'):
    • Returns the first HTMLElement object that matches the CSS selector.
    • Example:JavaScriptconst firstParagraph = document.querySelector('p.content'); console.log(firstParagraph); // Logs the HTMLParagraphElement object
  5. document.querySelectorAll('CSS-selector'):
    • Returns a static NodeList of all HTMLElement objects that match the CSS selector.
    • Example:JavaScriptconst allElements = document.querySelectorAll('h1, p, button'); console.log(allElements); // Logs a NodeList containing all three element objects

Common Properties and Methods of HTML Objects

Once you have an HTML object, you can interact with it using its properties and methods:

Common Properties:

  • id: Get or set the id attribute.JavaScripttitleElement.id = 'newTitleId';
  • className: Get or set the class attribute (as a string).JavaScriptfirstParagraph.className = 'highlight important';
  • classList: A DOMTokenList object for safer and easier manipulation of classes (add(), remove(), toggle(), contains()).JavaScriptfirstParagraph.classList.add('active'); firstParagraph.classList.remove('content'); firstParagraph.classList.toggle('hidden');
  • textContent: Get or set the plain text content of an element (no HTML parsing).JavaScripttitleElement.textContent = 'Updated Page Title';
  • innerHTML: Get or set the HTML content of an element (HTML is parsed).JavaScriptfirstParagraph.innerHTML = 'This is <strong>new</strong> paragraph content.';
  • style: An object containing inline CSS properties (camelCase).JavaScriptfirstParagraph.style.color = 'blue'; firstParagraph.style.fontSize = '20px';
  • tagName: Returns the tag name of the element in uppercase (e.g., “H1”, “P”).
  • value: Specific to form elements (<input>, <textarea>, <select>) to get/set their current value.HTML<input type="text" id="nameInput" value="Initial Name"> JavaScriptconst nameInput = document.getElementById('nameInput'); console.log(nameInput.value); // "Initial Name" nameInput.value = 'John Doe';
  • checked: Specific to radio buttons and checkboxes to get/set their checked state (boolean).HTML<input type="checkbox" id="agreeCheckbox" checked> JavaScriptconst agreeCheckbox = document.getElementById('agreeCheckbox'); console.log(agreeCheckbox.checked); // true agreeCheckbox.checked = false;

Common Methods:

  • setAttribute('name', 'value'): Sets an attribute’s value.JavaScriptconst myButton = document.querySelector('button'); myButton.setAttribute('data-id', 'btn-123');
  • getAttribute('name'): Gets an attribute’s value.JavaScriptconsole.log(myButton.getAttribute('data-id')); // "btn-123"
  • removeAttribute('name'): Removes an attribute.JavaScriptmyButton.removeAttribute('data-id');
  • appendChild(childNode): Adds a node as the last child of the element.JavaScriptconst newDiv = document.createElement('div'); newDiv.textContent = 'I am a new element!'; document.body.appendChild(newDiv);
  • removeChild(childNode): Removes a child node from the element.JavaScriptdocument.body.removeChild(newDiv);
  • addEventListener('event', handlerFunction): Attaches an event listener to the element.JavaScriptmyButton.addEventListener('click', () => { alert('Button clicked!'); });
  • remove(): A modern method to remove the element itself from its parent.JavaScriptfirstParagraph.remove(); // Removes the paragraph from the DOM

Understanding HTML objects is fundamental to building dynamic and interactive web applications with JavaScript. They are the bridge between your static HTML and the programmatic power of JavaScript, allowing you to manipulate every aspect of a web page in response to user actions or data changes.

Share the Post:

Related Posts