Home  >  Article  >  Web Front-end  >  Recommend 4 commonly used functions in native javascript_javascript skills

Recommend 4 commonly used functions in native javascript_javascript skills

WBOY
WBOYOriginal
2016-05-16 16:21:06951browse

【1】Add listening event

Copy code The code is as follows:

​​ addHandler:function(node,type,fn){if(node.addEventListener){
Node.addEventListener(type,fn,false); // false, set to bubbling event             }
            else{
Node.attachEvent('on' type,function(){
Fn.apply (node, arguments); // Attachevent method, this does not point to Node, so you need to use the Apply () method to change the
method                 });
            }
}

[2] Set the style of the element

Copy code The code is as follows:
setCss:function(node,val){ // val:{'top':'2px','font-size':'12px'}
for(var v in val){
                                                                                                                                                                                                      node.style.cssText = ';' v ':' val[v]; //Using cssText can set multiple attributes at the same time, and another advantage is that it can avoid the judgment of cssFloat, styleFloat
            }
}

【3】Get CSS class name element

Copy code The code is as follows:
//parent is an optional parameter,
       getByClassName:function(className,parent){
            var elem = [],
Node = parent != undefined&&parent.nodeType==1?parent.getElementsByTagName('*'):document.getElementsByTagName('*'),
                   p = new RegExp("(^|\s)" className "(
\s|$)"); for(var n=0,i=node.length;n If(p.test(node[n].className)){
                        elem.push(node[n]);
                }
            }
              return elem;
}

[4] Delete CSS class name

Copy code The code is as follows:
removeClassName:function(node,className){
var par = new RegExp(className,'g');
Node.className = node.className.replace(par,'');
}

The above 4 are very practical and frequently used native js functions that I have compiled. I recommend them to my friends. I hope they will be helpful to everyone.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn