Several self-encapsulated Javascript Functions, including the getId () function, getClass () function, addClass () function, and removeClass () function.
Several self-encapsulated Javascript Functions, including getId (), getClass (), addClass (), and removeClass (), now let's share it with you:
1. Get the id function getId ()
IdName: Element id, required
123 |
FunctiongetId (idName) {returndocument. getElementById (idName );} |
2. getClass ()
ClassName: Class Name, required;
Root: the closest id of the outer layer of the target class, which can be omitted. If omitted, document is used;
Tag: The tag Name of the target class, which can be omitted. If it is omitted, take *, that is, all labels under root.
1234567891011121314151617181920212223 |
FunctiongetClass (className, root, tag) {if (typeofroot = "string") {if (getId (root )! = Null) {root = getId (root);} else {tag = root; root = document;} else {root = document;} varels = root. getElementsByTagName (tag | ("*"), arr = []; for (vari = 0; I <els. length; I ++) {vartemp = els [I]. className. split (""); for (varj = 0; j <temp. length; j ++) {if (temp [j] = className) {arr. push (els [I]); break ;}} returnarr ;} |
3. Add the class function addClass ()
Node: the element of the class to be added. required;
Classname: Class Name, required
12345 |
FunctionaddClass (node, classname) {if (! NewRegExp ("(^ | \ s +)" + classname). test (node. className) {node. className = node. className + "" + classname ;}} |
4. Delete the class function removeClass ()
Node: the element of the class to be deleted. required;
Classname: Class Name, required
123 |
FunctionremoveClass (node, classname) {node. className = node. className. replace (newRegExp ("(^ | \ s +)" + classname ),"");} |
OK. The above is the content of this article. It seems that getClass () is a bit difficult to write, and the performance is not very good, but it is also for the latter two parameters to be optional. If the three parameters are required, you can also omit a lot of code. However, if you use this getClass () function, we recommend that you do not omit the last two parameters. In this way, the traversal elements will be a little less, and the performance may be better.