Add style class in js
Looking at js recently, it is king to lay a solid foundation. The underlying things cannot be ignored.
Adding style names in Js makes it easy to add and remove styles when using jQuery. But how to deal with js? I just read an article, the seven details that should be paid attention to by beginners of JavaScript at the cainiao level, in which I wrote something like this: I modified the style name and made some extensions.
I,
function addclass(elm,newclass){ var c = elm.className; if(c!="") elm.className=newclass;}
Write a function and pass in the object element and style name to determine whether it is empty. If it is not empty, assign a style name;
II,
function addclass(elm,newclass){ var c = elm.className; elm.className = (c =="") ? newclass : c+' '+newclass;}
Write a function, input the object element, and add it to the style name to determine whether it is null. If it is null, assign a value. Otherwise, add a space and assign a value;
III,
function addclass(elm,newclass){ var classes = elm.className.split(' '); classes.push(newclass); elm.className = classes.join(' '); }
Input the object element and style name, and then set elm. className is a string separated by a space. It is removed from the space and converted into an array using the split method. Then, the style is added to the Array Using the push method, it is a very unique and awesome method to add spaces to join and convert them into strings and then assign values to the class of the element.
However, I think it is a bit inadequate. What should I do if the element already has a newclass name? Like this:
Then I want to add a div2 class to this div. If the third method is used, although there will be no errors, the page will become like this, so I use the fourth method: ** 4 ,**
function zhen(obj,claName){ var cla=obj.className.split(" "); for(var i=0;i<cla.length;i++) {="" if(cla[i]="=claName)" return;="" }="" cla.push(claname);="" obj.classname="cla.join("" ");="" }
Based on the advantages of the third method, a circular decision is made to ensure that no duplicate names exist.