[Practical Summary] Dom node classname operations

Source: Internet
Author: User

The frequently used mini-tool functions are rewritten every time they are used, which is a waste of physical strength. So I decided to sort them out in stages and copy them for use ~

For the classname of a DOM node, common operations include adding, deleting, and querying. (You can add or delete a DOM node in advance .)CodeRelatively simple, directly add source code + Interface comments

/*** @ Description adds a class to the node * @ Param {domobject} node Dom node * @ Param {string} classname name of the class to be added */function addclass (node, classname) {var addclassname = trim (classname); var oriclassname = node. classname; If (oriclassname. indexof (addclassname) ===- 1) {node. classname = oriclassname + ''+ classname ;}} /*** @ description deletes a class of a node * @ Param {domobject} node Dom node * @ Param {string} classname name of the class to be deleted */Function Removeclass (node, classname) {var Reg = new Regexp ('\ B' + trim (classname) + '\ B', 'G'); node. classname = node. classname. replace (Reg ,'');} /*** @ description determines whether a node has a class * @ Param {domobject} node Dom node * @ Param {string} the class name queried by classname * @ return {Boolean} true- yes, false-No */function hasclass (node, classname) {return node. classname. indexof (TRIM (classname ))! =-1 ;} /*** @ Description: deletes the space at the beginning and end of a string * @ Param {string} STR original string * @ return {string} deletes the string after the first space * @ example trim ('Hello world ') === 'Hello world' */function trim (STR) {return Str. replace (/^ \ s + /,''). replace (/\ s + $ /,'');}

if multiple classes are added at the same time and multiple classes are deleted at the same time, the implementation principle is similar and will not be repeated.

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.