简体   繁体   中英

How can I change the label for css style?

I have a checkbox with label.

<input type="checkbox" name="comment" id="abc1" value="the value." 
 onclick="createOrder()"><label for="abc1" onclick="createOrder()" 
 title="title"> onscreen text for this checkbox </label>

In a javascript function, I want to change the appearance of the input. Here is an example that works (changes the element's visibility) but is not what I want to do:

if (n !== -1) {
     document.getElementById(id).style.visibility = "hidden";
    }

However, I don't want to make it invisible. I want to change the text color of the words associated with the checkbox ("onscreen text for this checkbox") The text would change from the default black to grey.

I don't know how to change the "label for" style. Can anyone help change the javascript? The result would simply change the color of the text.

As you said the code you're trying works so to target next node, you can use .nextSibling

if (n !== -1) {
   document.getElementById(id).nextSibling.style.color= "#c8c8c8"; //color you need"
}
else{
  document.getElementById(id).nextSibling.style.color= "#fefefe"; //Default color
}

You can do something like using jQuery: jQuery:

$(document).ready(function(ee){ 
 $("#abc1").click(function(){   
     if ($(this).is(':checked')) {       
         $(this).next().css({"color": "Red"});
     }else
     {
         $(this).next().css({"color": "black"});
     }
});  

});

HTML:

 <input type="checkbox" name="comment" id="abc1" value="the value." ><label for="abc1" title="title"> onscreen text for this checkbox </label>

This should work.

Thanks

it can easily be achieved, doesnt matter where the label is located or how many are there.

there is an answer Here that shows how to get elements by their attributes.

lets take the function from that answer, adjust it and use it for your question:

 //get all labels with for=abc1 attribute el=getLabelByForAttribute("abc1"); //loop through those labels and change their style el.forEach(function(elem,idx){ elem.style["color"]="grey"; }); function getLabelByForAttribute(a) { var matchingElements = []; //get all labels in the document var allElements = document.getElementsByTagName('label'); for (var i = 0, n = allElements.length; i < n; i++) { //if those labels have the required 'for' attribute if (allElements[i].getAttribute("for") ==a) { // Element exists with attribute. Add to array. matchingElements.push(allElements[i]); } } return matchingElements; } 
 <input type="checkbox" name="comment" id="abc1" value="the value." onclick="createOrder()"> <label for="abc1" onclick="createOrder()" title="title">onscreen text for this checkbox</label> 

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