4 common functions of native javascript are recommended

Source: Internet
Author: User

4 common functions of native javascript are recommended

This article mainly introduces the recommendation of four common native javascript Functions. For more information, see

 

 

[1] add listener events

 

The Code is as follows:


AddHandler: function (node, type, fn) {if (node. addEventListener ){
Node. addEventListener (type, fn, false); // false, set as a bubble event
}
Else {
Node. attachEvent ('on' + type, function (){
Fn. apply (node, arguments); // In the attachEvent method, this does not point to node, so you need to change it using the apply () method.
});
}
}

 

[2] set the element style

 

The Code is as follows:


SetCss: function (node, val) {// val: {'top': '2px ', 'font-size': '12px '}
For (var v in val ){
Node.style.css Text + = ';' + v + ':' + val [v]; // you can use cssText to set multiple attributes at the same time. Another benefit is to avoid cssFloat, determination of styleFloat
}
}

 

[3] retrieving CSS class name elements

 

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 <I; n ++ ){
If (p. test (node [n]. className )){
Elem. push (node [n]);
}
}
Return elem;
}

 

Iv. Delete the CSS Class Name

 

The Code is as follows:


RemoveClassName: function (node, className ){
Var par = new RegExp (className, 'G ');
Node. className = node. className. replace (par ,'');
}

 

The above four are native js functions that are very practical and frequently used. We recommend them to our friends and hope to help you.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.