Write me a plain and reusable JavaScript function to switch the content of a HTML span…
- User
Write me a plain and reusable JavaScript function to switch the content of a HTML span based on two radio controls. The span and the radio controls are in the same div with the class "switcher".
- Assistant
Sure! Here's a simple JavaScript function that switches the content of a span based on the value of two radio controls within the same div with the class "switcher":
function switchContent() { const switcherDiv = document.querySelector('.switcher'); const spanElement = switcherDiv.querySelector('span'); const radioInputs = switcherDiv.querySelectorAll('input[type="radio"]'); radioInputs.forEach(radio => { radio.addEventListener('change', () => { if (radio.checked) { spanElement.textContent = radio.value; } }); }); } switchContent();You can call this function whenever you want to initialize the functionality or run it on page load. Just ensure that you have the proper HTML structure with the radios and the span within the same
divelement with the class "switcher". - User
Make this function also reusable because there may be more than one div with the class "switcher" which should work independant to other divs on the page.
- Assistant
Sure! Here's an updated version of the function that makes it reusable for multiple
divelements with the class "switcher" on the page:function switchContent() { const switcherDivs = document.querySelectorAll('.switcher'); switcherDivs.forEach(switcherDiv => { const spanElement = switcherDiv.querySelector('span'); const radioInputs = switcherDiv.querySelectorAll('input[type="radio"]'); radioInputs.forEach(radio => { radio.addEventListener('change', () => { if (radio.checked) { spanElement.textContent = radio.value; } }); }); }); } switchContent();This updated function will iterate over all the
divelements with the class "switcher" and set up the functionality independently for each one. This way, the function can be reused for multiple instances of the switcher on the page. - User
Awesome, can you also generate me the HTML to test this function?
- Assistant
Sure! Here's a simple HTML code snippet that you can use to test the
switchContentfunction:<div class="switcher"> <input type="radio" name="radioGroup1" value="Option 1" checked> Option 1 <input type="radio" name="radioGroup1" value="Option 2"> Option 2 <span>Initial Content</span> </div> <div class="switcher"> <input type="radio" name="radioGroup2" value="Apple" checked> Apple <input type="radio" name="radioGroup2" value="Banana"> Banana <input type="radio" name="radioGroup2" value="Orange"> Orange <span>Initial Fruit</span> </div>This HTML code includes two
divelements with the class "switcher", each containing radio controls and a span element to display the content. You can place this HTML code in your web page and include the JavaScript function provided earlier to test the functionality of switching content based on radio control selection.