How to Change the Content of a Div with JavaScript
JavaScript provides various ways to manipulate elements on a web page, including the ability to change the content of a div. Let's demonstrate how this can be achieved using simple JavaScript code.
Consider the following HTML code:
<code class="html"><html> <head> <script type="text/javascript"> 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>
In this code, we have two radio buttons (A and B) and a div with an id of "content." The goal is to change the content of the "content" div when one of the radio buttons is selected.
To achieve this, we can use the innerHTML property of the content element. Here's how:
<code class="javascript">document.getElementById("content").innerHTML = "whatever";</code>
When you select the "A" or "B" radio button, the changeDivContent() function is called. In this function, you can set the innerHTML property of the content element to the desired text. For example:
<code class="javascript">function changeDivContent() { if (document.getElementById("radiobuttonA").checked) { document.getElementById("content").innerHTML = "Content for A"; } else if (document.getElementById("radiobuttonB").checked) { document.getElementById("content").innerHTML = "Content for B"; } }</code>
This code checks which radio button is selected and changes the content of the "content" div accordingly. You can customize the innerHTML value with the desired text you want to display. This technique allows you to dynamically change the content of a div based on user interactions, creating more interactive web pages.
The above is the detailed content of How do I dynamically change the content of a div using JavaScript based on user interaction?. For more information, please follow other related articles on the PHP Chinese website!