Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Dynamic DOM Manipulation with JavaScript

Tech May 16 1

Modifying Element Content

JavaScript provides two primary methods for updating content within DOM elements. The textContent property accesses text content while stripping HTML tags and collapsing whitespace:

contentContainer.textContent

Conversely, innerHTML preserves HTML structure and whitespace:

contentContainer.innerHTML

Practical implementation:

<div id="content-box"></div>
<p>
  Sample text
  <span>456</span>
</p>
<script>
  const contentBox = document.getElementById('content-box');
  contentBox.textContent = '<em>Current date:</em> 2023'; // Renders as plain text
  contentBox.innerHTML = '<em>Current date:</em> 2023'; // Renders with italic styling
</script>

Key distinctions:

  • textContent ignores HTML markup and standardizes whitespace
  • innerHTML processes HTML tags while preserving formatting
  • Both properties support read/write operations to content extraction

Standard Attribute Manipulation

Core attributes like src, href, and alt can be modified directly:

<button id="image-toggle">Switch Image</button>
<img src="assets/landscape.jpg" alt="Mountain view">

<script>
  const toggleBtn = document.getElementById('image-toggle');
  const imageElement = document.querySelector('img');
  
  toggleBtn.addEventListener('click', () => {
    imageElement.src = 'assets/sunset.jpg';
    imageElement.alt = 'Horizon scenery';
  });
</script>

Form Element Control

Form-specific properties require different handling approaches:

<button class="submit-btn">Submit</button>
<input type="text" value="Enter data">

<script>
  const submitBtn = document.querySelector('.submit-btn');
  const inputField = document.querySelector('input');
  
  submitBtn.addEventListener('click', () => {
    inputField.value = 'Processed';
    submitBtn.disabled = true;
    submitBtn.style.opacity = '0.6';
  });
</script>

Note that form values use the value property rather than content properties like innerHTML.

Runtime Styling Techniques

Two approaches exist for dynamic styling:

Inline Style Modification

<style>
  .box { width: 150px; height: 150px; background: #f0f0f0; }
</style>
<div class="box"></div>

<script>
  const visualBox = document.querySelector('.box');
  visualBox.addEventListener('click', () => {
    visualBox.style.backgroundColor = '#4a90e2';
    visualBox.style.width = '200px';
    visualBox.style.fontSize = '18px';
  });
</script>

Class-Based Styling

<style>
  .box { /* base styles */ }
  .active-state { 
    background: #e74c3c; 
    color: white; 
    transform: scale(1.1);
  }
</style>
<div class="box">Content</div>

<script>
  const interactiveBox = document.querySelector('.box');
  interactiveBox.addEventListener('click', () => {
    interactiveBox.className = 'box active-state';
  });
</script>

Important considerations:

  • CSS properties use camelCase notation (e.g., backgroundColor)
  • Inline styles override external CSS due to higher specificity
  • Class manipulation is preferable for complex style changes
  • The className property replaces all existing classes

Custom Data Atributes

For non-standard attributes, use dedicated methods:

<div id="data-element" data-item-id="789" category="electronics"></div>

<script>
  const dataElement = document.getElementById('data-element');
  
  // Reading attributes
  console.log(dataElement.getAttribute('category'));
  console.log(dataElement.dataset.itemId);
  
  // Modifying attributes
  dataElement.setAttribute('data-item-id', '101');
  dataElement.dataset.category = 'accessories';
  
  // Removing attributes
  dataElement.removeAttribute('category');
</script>

HTML5 standardizes custom data through data-* attributes:

  • Access via dataset property using camelCase (e.g., data-product-namedataset.productName)
  • Standard attributes should use direct property access (e.g., element.id)
  • Custom attributes require getAttribute/setAttribute methods
Tags: javascript

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.