Home >Web Front-end >JS Tutorial >How to Dynamically Change Div Content Using JavaScript?
Dynamically Modifying Div Content Using JavaScript
Altering the content of a div element with JavaScript can be achieved with an intuitive approach. The following HTML code snippet serves as an example:
<code class="html"><html> <head> <script> function changeDivContent() { /* ... */ } </script> </head> <body> <input type="radio" name="radiobutton" value="A" onClick="changeDivContent()"> <input type="radio" name="radiobutton" value="B" onClick="changeDivContent()"> <div id="content"></div> </body> </html></code>
Within this example, the objective is to modify the inner HTML content of div#content based on the user's selection of radio buttons with values "A" or "B." However, the div element lacks a JavaScript attribute "value" to facilitate this action.
To address this, JavaScript provides a straightforward solution by utilizing the innerHTML property of the HTML element. By implementing the following code:
<code class="js">document.getElementById("content").innerHTML = "whatever";</code>
within the changeDivContent() function, you can dynamically set the content of div#content to any desired value. This enables you to seamlessly update the content of a div element based on user input or other dynamic conditions within your JavaScript code.
The above is the detailed content of How to Dynamically Change Div Content Using JavaScript?. For more information, please follow other related articles on the PHP Chinese website!