Skip to content

Instantly share code, notes, and snippets.

@mrfoxtalbot
Created September 14, 2019 16:50
Show Gist options
  • Save mrfoxtalbot/48e835388165c18ab551115a9f2ad1bf to your computer and use it in GitHub Desktop.
Save mrfoxtalbot/48e835388165c18ab551115a9f2ad1bf to your computer and use it in GitHub Desktop.
JS Add or replace content on one or several HTML elements using a CSS selector
document.querySelector('.haiku').innerText = ('This is a Haiku')
// This will replace the content inside the first element that matches that CSS selector.
document.querySelectorAll('.haiku')[2].innerText = ('This is a Haiku')
// This will add a (.haiku) to the third element that matches that CSS selector.
document.querySelectorAll('.haiku').forEach(function(i){i.innerText = ('This is a Haiku')})
// This will replace the content of all elements that match that CSS selector
//There are ways to add content before and after the existing content instead of replacing it
// append to the element's content
el.innerHTML += '<p&gt;Hello World!</p&gt;';
// prepend to the element's content
el.innerHTML = '<p&gt;Hello World!</p&gt;' + el.innerHTML;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment