简体   繁体   中英

Add style on parent element of multiple set of radio buttons when checked without using jquery

I have a problem of converting jquery code to javascript. Theres a set of radio buttons and i need to add a style on its parent element just like this example .

Every selection of each set of radio buttons a style will be added to its parent. I need to work it using only Javascript.

Here's the Demo : The effect should be similar to that first link.

ie

<ul>
    <li class="check"><label for="one">1<input type="radio" id="one" name="test"/></label>     
    </li>
    <li class="check"><label for="two">2<input type="radio" id="two" name="test"/></label>
    </li>
</ul>
<ul>
    <li class="check"><label for="one">1<input type="radio" id="one" name="test2"/></label>
    </li>
    <li class="check"><label for="two">2<input type="radio" id="two" name="test2"/></label>
   </li>
</ul>
<ul>
    <li class="check"><label for="one">1<input type="radio" id="one" name="test3"/></label>
    </li>
    <li class="check"><label for="two">2<input type="radio" id="two" name="test3"/></label>
    </li>
</ul>

This code provides the expected functionality without jQuery:

function changeEvent(event) {
    //add highlight class
    this.parentNode.classList.add("highlight");
    try {
        //remove highlight class from previously selected radio in group
        //if already existing
        this.parentNode.parentNode.highlightDIV.classList.remove("highlight");
    } catch (ignore) {}
    //keep the highlighted div as a property of the parent div
    this.parentNode.parentNode.highlightDIV = this.parentNode;
}

//select all radio buttons
var radioList = document.querySelectorAll('input[type="radio"]');
//loop through list and add event listener
for (var i = 0; i < radioList.length; i++) {
    radioList[i].addEventListener("change", changeEvent, false);
}

It uses references to parentNode but they can be replaced by algorithms to dynamically find the wanted nodes in a more dynamic structure. I hope you get the direction and you may improve and modify the code to fit into your applications needs.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM