Modifying the content of a div element using JavaScript is a common task in web development. This article will guide you through the steps involved, even if the div lacks a "value" attribute.
Imagine you have the following HTML code:
<code class="html"><div id="content"></div> <input type="radio" name="radiobutton" value="A" onClick="changeDivContent()"> <input type="radio" name="radiobutton" value="B" onClick="changeDivContent()"></code>
You want to be able to change the content of the div element by selecting either the "A" or "B" radio buttons.
Since there isn't a "value" attribute for the div, you can use the innerHTML property of the element to set its content.
The following JavaScript function accomplishes this:
<code class="js">function changeDivContent() { let selectedValue = document.querySelector('input[name=radiobutton]:checked').value; document.getElementById("content").innerHTML = selectedValue; }</code>
Here's a breakdown of the code:
By clicking on either "A" or "B," this function will update the text inside the div element.
The above is the detailed content of How to Dynamically Update Div Content with JavaScript: A Guide Using Radio Buttons. For more information, please follow other related articles on the PHP Chinese website!