Click here to Skip to main content
15,915,094 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
can some one explain the below shim step by step . COuld never understand the regexp and if blocks below

JavaScript
document.getElementsByClassName= function( className, nodeName ){
    var a = [];
    var re = new RegExp('(^| )'+className+'( |$)');
    var els = nodeName.getElementsByTagName("*");
    for(var i=0,j=els.length; i<j; )
       if(re.test(els[i].className))
            a.push(els[i]);
    return a;
}
Posted
Updated 14-May-16 19:08pm
v3

To understand regular expressions you need to study them and try different expressions in a test tool.

Here is a pretty good site for learning about regular expressions:
Regular-Expressions.info - Regex Tutorial, Examples and Reference - Regexp Patterns[^]

The tool I usually use is RegExTest download | SourceForge.net[^] and it is free and pretty simple to use.

Another one is Expresso Regular Expression Tool[^] and is also free.

The regular expression used in your code basically means: Match the class name in a string.

Not sure where you get this code, though, as there is a predefined method already.
See HTML DOM getElementsByClassName() Method[^]
 
Share this answer
 
In addition to Solution 2
Debuggex: Online visual regex tester. JavaScript, Python, and PCRE.[^]
is a nice tool to check what a RegEx is really doig.
 
Share this answer
 
No, this is not "What I have tried". If you really tried it by yourself, you would not ask for the explanation. Such explanations are counter-productive. It's not clear what should be explained, based on what level of knowledge. Even more importantly, it can take enormous amount of time and turn out completely useless.

Reading someone else's code which you don't understand is not a real way of learning. You can rather learn by reading manuals and documentation and writing code by yourself.

As to the API you are asked about in the title of the question, this is the function which returns array-like object. This is well explained here: Document.getElementsByClassName() — Web APIs | MDN[^].

If something is unclear in this explanation, you should rather start learning JavaScript and general programming from scratch. Perhaps you can start with JavaScript | MDN[^].

—SA
 
Share this answer
 
Comments
Patrice T 15-May-16 1:05am    
Cleaned the question.
Sergey Alexandrovich Kryukov 15-May-16 1:45am    
Thank you.
—SA

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900