One data grid for JavaScript, React, Vue & Angular. Sorting, filtering, virtualization, pinning, and CSV export included. Early access $199 $349 → [Get it now]

How to change the HTML of an element in JavaScript

Changing element HTML content is essential for dynamic content updates, templating, and creating interactive user interfaces. As the creator of CoreUI with extensive JavaScript experience since 2000, I’ve implemented HTML content manipulation in countless UI components and data-driven applications. From my expertise, the most versatile approach is using the innerHTML property which allows setting both text and HTML markup dynamically. This method provides flexible content management while enabling rich formatting and nested element structures.

Use the innerHTML property to set HTML content including markup and nested elements.

const element = document.getElementById('myElement')
element.innerHTML = '<span class="highlight">Updated content</span>'

Here document.getElementById('myElement') selects the target element, and element.innerHTML = '<span class="highlight">Updated content</span>' replaces the entire HTML content inside that element. The innerHTML property interprets the string as HTML markup, creating new DOM nodes for any tags included. This allows inserting formatted text, images, links, and complex nested structures dynamically.

Best Practice Note:

This is the same approach we use in CoreUI components for dynamic content rendering and template-based updates. Be cautious with user-generated content to prevent XSS attacks - sanitize HTML or use textContent for plain text to ensure security.


Speed up your responsive apps and websites with fully-featured, ready-to-use open-source admin panel templates—free to use and built for efficiency.


About the Author

Subscribe to our newsletter
Get early information about new products, product updates and blog posts.
How to Detect a Click Outside of a React Component
How to Detect a Click Outside of a React Component

CSS Selector for Parent Element
CSS Selector for Parent Element

How to Convert a Map to an Array in JavaScript
How to Convert a Map to an Array in JavaScript

How to Center a Button in CSS
How to Center a Button in CSS