TIL different ways to inject content via Javascript
POSTED ON:
TAGS: html javascript
There's lots of ways to do things in Javascript. It gets difficult to know which way is the "preferred" way.
innerHTML
and outerHTML
#
<div class="greeting">
<p>Hello world!</p>
</div>
<script>
let greeting = document.querySelector('.greeting');
// Method 1: innerHTML
// set the HTML content inside an element as a string.
console.log(greeting.innerHTML); // returns "<p>Hello world!</p>"
greeting.innerHTML = '<p>A new paragraph</p>';
// Method 2: outerHTML
// Completely replaces the entire element
console.log(greeting.innerHTML); // returns "<div class="greeting"><p>Hello world!</p></div>"
greeting.outerHTML = '<p class="outro">Goodbye, friend! <a href="exit.html">Click here to leave.</a>';
</script>
textContent
and innerText
#
textContext
grabs everything.
innerText
is only visible data.
div class="greeting">
<style type="text/css">
p {
color: rebeccapurple;
}
</style>
<p hidden>This is not rendered.</p>
<p>Hello world!</p>
</div>
<script>
let greeting = document.querySelector('.greeting');
// Method 3: textContent method
let text = greeting.textContent; // returns "p {color: rebeccapurple;} This is not rendered. Hello world!"
greeting.textContent = 'We can dynamically change the content.';
// Method 4: innerText method
let text = elem.innerText; // returns "Hello world!"
greeting.innerText = 'We can dynamically change the content.';
</script>
[Four different ways to inject text and HTML into an element with vanilla JavaScript](https://gomakethings.com/four-different-ways-to-inject-text-and-html-into-an-element-with-vanilla-javascript/)
Related TILs
Tagged: html