Cover Image for Javascript – innerHTML
276 views

Javascript – innerHTML

The JavaScript innerHTML property is used to get or set the HTML content of an element. It can be used to access or modify the entire HTML content of an element, including any child elements, text content, and attributes.

Here is an example of using innerHTML to get the content of an element:

HTML<span role="button" tabindex="0" data-code="<div id="myDiv">     <h1>Heading</h1>     <p>Some text</p>
<div id="myDiv">
    <h1>Heading</h1>
    <p>Some text</p>
</div>
JavaScript<span role="button" tabindex="0" data-code="let myDiv = document.getElementById('myDiv'); let content = myDiv.innerHTML; console.log(content); // Output: "<h1>Heading</h1><p>Some text

let myDiv = document.getElementById('myDiv');
let content = myDiv.innerHTML;
console.log(content); // Output: "<h1>Heading</h1><p>Some text</p>"

In the above example, getElementById is used to get the element with the ID “myDiv”. Then, the innerHTML property is used to get the HTML content of the element, which is a string containing the h1 and p elements and their contents.

Here is an example of using innerHTML to set the content of an element:

HTML<span role="button" tabindex="0" data-code="<div id="myDiv"> <h1>Heading</h1> <p>Some text</p>
<div id="myDiv">
   <h1>Heading</h1>
   <p>Some text</p>
</div>
JavaScript<span role="button" tabindex="0" data-code="let myDiv = document.getElementById('myDiv'); myDiv.innerHTML = '<h2>New heading</h2><p>New text

let myDiv = document.getElementById('myDiv');
myDiv.innerHTML = '<h2>New heading</h2><p>New text</p>';

In the above example, getElementById is used to get the element with the ID “myDiv”. Then, the innerHTML property is used to set the HTML content of the element to a new string containing h2 and p elements and their contents. This will replace the original contents of the div element with the new HTML content.

It’s important to be careful when using innerHTML, as it can be vulnerable to cross-site scripting (XSS) attacks if the content being set contains user-generated or untrusted content. It’s generally recommended to use other methods, such as textContent, to set text content instead of innerHTML to avoid this vulnerability.

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS