Created
September 14, 2019 16:50
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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>Hello World!</p>'; | |
// prepend to the element's content | |
el.innerHTML = '<p>Hello World!</p>' + el.innerHTML; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment