Simple Javascript selector tutorial

Source: Internet
Author: User

Author: Ruby's Louvre

Original article: http://www.cnblogs.com/rubylouvre/archive/2009/11/22/1608053.html

I was going to start talking about jQuery source code study note 6, but there are Buddha in my heart to see Buddha. Some people don't even know anything about selector. Let's talk about it directly. It is estimated that someone will see the cloud in the fog, it's full of fog. In addition, John Resig has the magic of writing code to Alibaba Cloud. He has the power of the code, and he can see it by himself. Others will be killed. It is often a code that calls several methods, each of which is separated by dozens or even hundreds of lines, and these methods are often used as a guise. Other code is used to really do things. In this way, the code of the root node and Base2 can be combined. Finally, the selector itself is also very complicated. It must be put forward independently.

The selector has already been implemented, but it is an unremarkable but extraordinary method: getElementById, getElementsByName, getElementsByTagName. However, when foreigners are not satisfied with these APIs, they developed getElementsByClassName. Instead, they used getElementsBySelector to support all the currently published CSS2.1 delimiters! Then Prototype uses a $ and a $ to enclose them. The reason for this is obviously easy to understand. If one is returned, no index number is needed! Like jQuery, no matter how many items are returned, they are all wrapped in jQuery objects. They must use the index number or get method to retrieve the real DOM elements. Therefore, they are similar to $, so $ unified the world!

But how many items does the selector actually include? Calculate the ID selector, tag selector, Union selector, attribute selector, relationship selector, and pseudo-class selector. The ID selector starts with #. The tag selector is the tagName, the Union selector is the comma, and the attribute selector is the field enclosed in brackets, which is also very complicated, you can only use the attribute name without the attribute value. If the attribute value exists, it can be matched in several situations. (For details, see getElementsByAttribute in another blog.) For example, getElementsByName should be merged into the attribute selector because name is also an attribute. The link selector is subdivided into four sub-operators: Brother (~), Parent-Child (>), adjacent (+) and descendant (Space ). The pseudo-class selector has a very large number of Members, because the new pseudo-class selector in CSS3 is also like this. In addition to the pseudo-element selector, a small number of pseudo-elements such as the page pseudo-class and link pseudo-class cannot be converted to the selector. These qualified pseudo classes include the target pseudo class, structure pseudo class, language pseudo class, and UI state pseudo class. The language pseudo-classes are similar to the UI state pseudo-classes and attribute selector, so the implementation methods are also consistent. For the target pseudo class, we can intercept the parameters in the address bar and use the IE selector. The structure pseudo class is also a big family, divided into two schools: root and others. : Root is the root node documentElement. Other sub-element filters can be collectively referred to. We can filter them by Order (nth-child) and select (only-of-type) by type ), you can also choose the combination type and sequence, or you can choose empty based on whether there is any content in the element. There are also some variants, such as those with first and last. In jQuery, John Resig defines many quick choices to take care of those artists. Read this document for yourself.

Brother Selector

<! Doctype html> 

Tip: the code can be modified before running!

Adjacent Selector

<! Doctype html> 

Tip: the code can be modified before running!

Parent-Child Selector

<! Doctype html> 

Tip: the code can be modified before running!

Let's talk about its implementation principles. Generally, a string is selected and a group of elements are returned. If the string is "# aaa", you can simply cut down the previous "#" and use getElementsById to find it! If "p span" means to retrieve the span element of all p elements, we first use document. getElementsByTagName ("p") obtains all p elements, traverses p in it, and uses currentP. getElementsByTagName ("span. But this is the ideal situation. How can we call these Apis? # Remind us to use the IE selector, but if # is contained in quotation marks, such as p ["gh # erewf"], there is also # here. Therefore, we must take a look at the strings. For example, we must remove the blank spaces on both sides and remove unnecessary spaces in the strings. Each Blank Space occupies only one character space, let us know that the selector of those descendants is unnecessary. Let's look at how jQuery works:

// A long selector var str = "# div, h1 # id. class> span [dd = '2017> 100'] ul + li ,. class: contain (\ "+ + 999 \"), strong span "; var chunker = /((? :\((? : \ ([^ ()] + \) | [^ ()] +) + \) | \[(? : \ [[^ [\] * \] | ['"] [^'"] * ['"] | [^ [\]'"] +) + \] | \\. | [^> + ~, (\ [\] +) + | [> + ~]) (\ S *, \ s *)? /G; var a = str. match (chunker); alert ()

Tip: the code can be modified before running!

A very powerful regular expression, but this will not be visible to future generations. jQuery will do some remedial measures in the future. In fact, many aspects of jQuery are not in place in one step. One method calls another method. In the end, it is not very meaningful to convert it into an array. Other regular expressions are needed for further processing, both of them require further regular matching to analyze whether the current array element is an ID selector or an attribute selector.

It seems that you like jQuery, so let's look at jQuery. Other class libraries use many regular expressions to process strings and obtain the desired information. JQuery looks pretty and clear, and the Implementation inside is really complicated and disgusting. Maybe John Resig is a dark man. he published the source code but didn't want others to understand it. He deliberately wrote it like this. I suspect that the comments in the source code are for the other two authors of jQuery ...... Well, I guess it all. Let's look at the implementation process. The above IDs, class, name, attr, and so on are basically done using the two selectors document. getElementById and element. getElementsByTagName plus getAttribute. We can select the correct element only when every element node has this method. Each time we get a bunch of elements, check their attributes one by one and locate the parent element one by one, and put the results in an array. Then we will repeat this step next time. Sometimes, when both elements have the same child element, we need to make some tags on these elements. If they are not included in the array, they will be skipped. As for how to implement these functions, this is the jQuery source code. The following table is attached:

Start character Indicates the selector. Judgment Method
# ID Selector /#((? : [\ W \ u00c0-\ uFFFF _-] | \.) + )/
. Class Selector /\.((? : [\ W \ u00c0-\ uFFFF _-] | \.) + )/
  Descendant Selector /^ \ S */
[ Attribute Selector /\ [\ S *((? : [\ W \ u00c0-\ uFFFF _-] | \.) +) \ s *(? :( \ S? =) \ S * (['"] *) (. *?) \ 3 |) \ s * \]/
+ Adjacent Selector /^ [> \ + \ ~] /
~ Brother Selector /^ [> \ + \ ~] /
> Parent-Child Selector /^ [> \ + \ ~] /
: Pseudo-class selector /:((? : [\ W \ u00c0-\ uFFFF _-] | \.) + )(? : \ (['"] *) (? : \ ([^ \)] + \) | [^ \ 2 \ (\)] *) +) \ 2 \))? /
, Joint Selector /,/
Letter Tag Selector /^ ((? : [\ W \ u00c0-\ uFFFF \ * _-] | \.) + )/

Related Article

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.