Using JS to implement jquery's AddClass, Removeclass, hasclass function _javascript skills

Source: Internet
Author: User

Nonsense not much to say that directly on the code

Copy Code code as follows:

function addclass (obj, CLS) {
var Obj_class = obj.classname,//Gets the class content.
Blank = (Obj_class!= ")? ":"//To determine whether the acquired class is empty, and add a ' space ' to the front if it is not empty.
Added = Obj_class + blank + cls;//combines the original class and the class that needs to be added.
Obj.classname = added;//replaces the original class.
}

function Removeclass (obj, CLS) {
var obj_class = ' +obj.classname+ '; Get the class content and add a space to the end. EX) ' ABC BCD '-> ' abc BCD '
Obj_class = Obj_class.replace (/(\s+)/gi, ""),//replaces extra empty characters with a single space. EX) ' ABC BCD '-> ' abc BCD '
removed = Obj_class.replace (' +cls+ ', ');//Replace the class with space in the original class. EX) ' ABC BCD '-> ' BCD '
removed = Removed.replace (/(^\s+) | ( \s+$)/g, "")//Remove the trailing space. Ex) ' BCD '-> ' BCD '
Obj.classname = removed;//replaces the original class.
}

function Hasclass (obj, CLS) {
var Obj_class = obj.classname,//Gets the class content.
Obj_class_lst = Obj_class.split (/\s+/);//The CLS is converted to an array by a split null character.
x = 0;
for (x in Obj_class_lst) {
if (obj_class_lst[x] = = CLS) {//loop array, determining whether to include CLS
return true;
}
}
return false;
}

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.