Explain Codes LogoExplain Codes Logo

How can I change div content with JavaScript?

javascript
event-delegation
dom-manipulation
accessibility
Nikita BarsukovbyNikita Barsukov·Dec 29, 2024
TLDR

To promptly change a div's text in JavaScript, utilize:

document.getElementById('targetDiv').textContent = 'Updated text';

To incorporate HTML elements within the content:

document.getElementById('targetDiv').innerHTML = '<b>Updated</b> content';

Here, textContent is your go-to for plain text, while innerHTML works magic with HTML tags. Remember that "With great power, comes great responsibility of not messing up your HTML".

Changing content dynamically

Often we are required to adapt our content based on user behavior. This is how to alter div content based on radio button selection:

// Function to update content function updateContent(value) { document.getElementById('targetDiv').innerHTML = value; } // An event listener to sense the disturbance in the force (read: radio button selection) document.getElementById('myRadioButton').addEventListener('change', function() { updateContent(this.value); // Call Yoda, the force is strong with this one });

Ensure all your Jedi knights (read: radio buttons) share the same family name (er, name attribute).

Delegation — the unsung hero

With multiple radio buttons, event delegation is your light at the end of the tunnel:

// The guiding lighthouse, acting upon the cries of its minions (read: radio buttons). document.querySelector('#radioContainer').addEventListener('change', function(event) { if(event.target.type === 'radio') { updateContent(event.target.value); // Update and adapt, that's the game } });

Event delegation ensures your handlers aren’t lazing around on each button.

querySelector to the rescue

For those who value flexibility over tradition, querySelector is your power tool:

document.querySelector('.targetClass').innerHTML = 'New content';

querySelector is versatile and lets you grab elements by their CSS selectors, no matter how stylish they are!

jQuery — the fancy cousin

For those who want to jazz it up a bit, jQuery can add some rhythm:

$('#targetDiv').html('New <i>HTML</i> content'); // Jazz hands here!

Remember, .html() method is the belle of the jQuery ball, equivalent to innerHTML.

Test like there's no tomorrow

Always test your code until you can't tell a div from a span. Compare your JS performances, optimize if needed, and make jsperf.com your new homepage.

Remember, Javascript might act like that one friend who behaves differently at every party — so make sure to test across various browsers!

Accessibility — Not all heroes wear capes

Accessibility matters. Remember, not every hero wears a cape. Some use screen readers. So, when making updates, ensure your changes are noticeable or pair them with ARIA attributes for better accessibility.