📅  最后修改于: 2023-12-03 15:15:50.372000             🧑  作者: Mango
In JavaScript, innerHTML
is a property of HTML elements that allows you to get or set the HTML content inside an element. It is a powerful tool that can be used to manipulate the content of a webpage dynamically.
element.innerHTML = newContent;
The element
variable represents the HTML element that you want to modify, and the newContent
variable represents the new HTML content that you want to add to the element.
<!DOCTYPE html>
<html>
<head>
<title>JavaScript InnerHTML Example</title>
<script>
function addText() {
var element = document.getElementById("myElement");
element.innerHTML = "Hello World!";
}
</script>
</head>
<body>
<button onclick="addText()">Click me</button>
<div id="myElement"></div>
</body>
</html>
In this example, we have a button element that, when clicked, calls the addText()
function. The function retrieves the HTML element with the ID myElement
, and sets its innerHTML
property to the string "Hello World!". This causes the text "Hello World!" to be displayed on the webpage inside the myElement
div.
innerHTML
is easy to use and understand.innerHTML
can be vulnerable to cross-site scripting (XSS) attacks if you are inserting user-generated content into the HTML.innerHTML
to modify styles or event listeners as this can often lead to unexpected results.innerHTML
is a powerful and versatile tool for making dynamic changes to the content of a webpage using JavaScript. However, it is important to use it responsibly and be aware of its potential drawbacks. With proper use, innerHTML
can help you create dynamic, interactive, and engaging webpages.