简体   繁体   中英

Changing style using JS & HTML works, JS & CSS doesn't always

Using JS & HTML markup Always works: Codepen

if (document.forms['myForm'].name.value == '') {
    name.style.background = "pink";
}
else {
    name.style.background = "white";
}

Using JS & CSS Doesn't always work: Codepen

if (document.forms['myForm'].name.value == '') {
    // give this element the .error class from the css file
    name.className = name.className + " error";
}
else {
    // this removes the error class
    name.className = name.className.replace(" error", ""); 
}

Why is JS & CSS inconsistent? I would like to use this approach since I can just apply an error class to each of the elements I want to effect.

Everytime you hit your submit button and a field isn't filled out, error is added to the classList property; if you submit more than once, multiple classes will be added. Whereas when removing the class, .replace(' error', '') will only replace the first instance of error it comes across.

You can use regex to find all instances of error :

name.className = name.className.replace(/ error/g, "");

Codepen

Sidenote: You can take advantage of classList but its browser support is limited.

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