innerHTML
In this tutorial, you will learn about the innerHTML property in JavaScript.
The innerHTML property is a part of the JavaScript HTMLElement object and it allows developers to access and manipulate the HTML content of an element. The innerHTML property returns the content between the opening and closing tags of an element, as a string of HTML.
Syntax
The syntax for accessing the innerHTML property is as follows:
element.innerHTML;Where element is a reference to the HTML element whose content you want to access or modify.
Example
Let's consider the following HTML code:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>innerHTML Example</title>
</head>
<body>
<div id="example">
<p>Hello, World!</p>
</div>
<script src="script.js"></script>
</body>
</html>In the above code, we have a div element with an id of example and a p element with the text "Hello, World!".
Now, let's access the innerHTML property of the div element using JavaScript:
const element = document.getElementById("example");
console.log(element.innerHTML);The output of the above code will be:
<p>Hello, World!</p>Modifying the innerHTML
You can also modify the innerHTML property to change the content of an element. For example, let's change the content of the div element to "Hello, JavaScript!" using the innerHTML property:
const element = document.getElementById("example");
element.innerHTML = "<p>Hello, JavaScript!</p>";After running the above code, the content of the div element will be updated to "Hello, JavaScript!".
Security Considerations
It is important to note that using the innerHTML property can expose your application to cross-site scripting (XSS) attacks if you are not careful. When setting the innerHTML property, make sure to sanitize the input to prevent malicious code injection.
Conclusion
- The
innerHTMLproperty allows you to access and modify the HTML content of an element. - You can use the
innerHTMLproperty to get the content between the opening and closing tags of an element. - You can also modify the
innerHTMLproperty to change the content of an element. - Be cautious when using the
innerHTMLproperty to preventXSSattacks.
How is this guide?
Sign in to share your feedback
Help us improve by sharing your thoughts on this guide.
Last updated on