JS Modify Content Dom

In JavaScript, modifying content in the DOM allows you to dynamically change the text, HTML structure, or even remove content in a webpage. Below are the common methods to manipulate content in the DOM:


textContent:

  • Updates or retrieves the text inside an element.
  • Strips any HTML tags and treats everything as plain text.
Example
<div id="example">Existing text</div>
<script>
const element = document.getElementById('example');
element.textContent = 'This is updated text!';
console.log(element.textContent); // Output: This is updated text!
</script>

Try it yourself


innerHTML:

  • Sets or retrieves the HTML content inside an element.
  • Allows you to insert HTML tags as well.
Example
<div id="example">Existing text</div>
<script>
const element = document.getElementById('example');
element.innerHTML = '<strong>Bold Text</strong>';
console.log(element.innerHTML); // Output: <strong>Bold Text</strong>
</script>

Try it yourself


outerHTML:

  • Sets or retrieves the HTML of the element itself, including the element tag.
Example
<div id="example">Existing text</div>
<script>
const element = document.getElementById('example');
console.log(element.outerHTML); // Outputs the entire element, e.g., <div id="example">...</div>
element.outerHTML = '<p>Replaced element!</p>'; // Replaces the entire element.
</script>

Try it yourself


value:

  • Get value from input element
Example
<h1>value in js</h1>
<input id="example" type="text" value="whereisstuff" />
<p>Open console in browser then you will see output</p>
<div id="bindInput"></div>
<script>
const element = document.getElementById('example');
console.log(element.value); // Outputs whereisstuff
const bindInput = document.getElementById('bindInput');
bindInput.innerHTML = element.value;
</script>

Try it yourself


Whereisstuff is simple learing platform for beginer to advance level to improve there skills in technologies.we will provide all material free of cost.you can write a code in runkit workspace and we provide some extrac features also, you agree to have read and accepted our terms of use, cookie and privacy policy.
© Copyright 2024 www.whereisstuff.com. All rights reserved. Developed by whereisstuff Tech.