简体   繁体   中英

change classname of parent span element using javascript

how can we change classname of parent span element on click of input radio button.

 <label for="L"> <span class="lbllevel1"> <span class="label-size">L</span> <input id="L" name="size" type="radio" value="L"> </span> </label> 

I want to add "selected" class to span element which is with class "lbllevel1" on click of radio button.

Basically, i need output as <span class="lbllevel1 selected"> when radio button is clicked

you can add an event listener to radio button for click event or change event, use document.getElementById('L') to get the input, and inside event handler function use e.currentTarget to get current clicked input, you can use .classList += to add class to element, something like this:

 var input = document.getElementById('L'); input.addEventListener("click", function(e){ e.currentTarget.parentElement.classList += ' selected'; }) 
 .selected{ background-color:#888888; } 
 <label for="L"> <span class="lbllevel1"> <span class="label-size">L</span> <input id="L" name="size" type="radio" value="L"> </span> </label> 

var lInput = document.getElementById("L");
lInput.addEventListener("click", function() {
    lInput.parentNode.classList.add("selected");
})

You could listen to the change event of radio by then add parent element with selected class if radio is checked:

document.querySelector("#L").addEventListener("change", function () {
  // check if radio is checked
  if (this.checked)
  {
     // add .selected class to parent
     this.parentElement.classList.add("selected");
  }
});

working copy

<label for="L">
<span class="lbllevel1">
      <span class="label-size">L</span>
      <input id="L" name="size" onclick="changeAttr(this)" type="radio" 
value="L">
  </span>
</label>

<script>

 function changeAttr(ele)
{
    ele.parentElement.classList.add('newClass');
}

</script>

Please see if this is helpful or not :)

Check through name

if($("input:radio[name='Name']").is(":checked")) {
         //write your code         
}

Check through class

if($("input:radio[class='className']").is(":checked")) {
     //write your code         
}

Check through data

if($("input:radio[data-name='value']").is(":checked")) {
         //write your code         
}

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