search
HomeWeb Front-endHTML TutorialCSS Journey (2): How to understand various selectors more deeply_html/css_WEB-ITnose

Original source: First-line coder



In the last article we talked about why we should use css. In this article we will start with the selector. Everyone knows The browser will parse the remote HTML into a dom model. With the dom model, the html will become an xml format. Otherwise, it will be a bunch of "messy" strings. In this case, no one will know what it is, and js will not There is no way to getElementById, so when the browser parses it into a dom structure, the browser will easily find the corresponding position in the dom structure according to the selectors of various CSS rules. Then the next problem will naturally be serious, then It is necessary to understand the dom model in depth.

1: Understanding the Dom model

First we look at the code below.

<!DOCTYPE html><html xmlns="http://www.w3.org/1999/xhtml"><head>    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />    <title></title></head><body>    <p>有名的公司一栏</p>    <hr />    <ul>        <li>百度</li>        <li>新浪</li>        <li>阿里</li>    </ul></body></html>

Using this code we can easily draw the dom tree.

When you see this DOM tree, do you suddenly feel that the amount of information is particularly large? It is very simple, because it is a tree, so there are some trees Characteristics, such as "child node", "father node",

"sibling node", "first left child", "last left child", etc., correspond to the various things I will talk about later. In this case, let’s see if it feels good to see the html being stripped naked~~~~

1: Child node

Finding child node, essentially there are two types, Really only find "child nodes", "find all children (including descendants)"

Descendant Selector

First look at the html below, I think you can draw it easily Now that the DOM tree is out, the next question is how to paint all descendant spans in the body with red.

<!DOCTYPE html><html xmlns="http://www.w3.org/1999/xhtml"><head>    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />    <title></title>    <style type="text/css">        body span {            color: red;        }    </style></head><body>    <span>我是span1</span>    <ul>        <li>            <ul><span>我是span2</span></ul>        </li>    </ul></body></html>

2. Child selector

”>” How to play

This is also the second situation I mentioned , it really only looks for child nodes. It’s very simple in CSS, just use the > sign. Isn’t it interesting? It’s the same way as jquery, right?

<html xmlns="http://www.w3.org/1999/xhtml"><head>    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />    <title></title>    <style type="text/css">        body > span {            color: red;        }    </style></head><body>    <span>我是span1</span>    <ul>        <li>            <ul><span>我是span2</span></ul>        </li>    </ul></body></html>

"Pseudo-selector" gameplay

In addition to the above gameplay, you can also use the "pseudo-selector" gameplay in CSS3. It’s so powerful. The next article will explain it specifically. Here I only introduce one: nth-child usage. If

you have played with jquery, nothing will be a problem.

<!DOCTYPE html><html xmlns="http://www.w3.org/1999/xhtml"><head>    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />    <title></title>    <style type="text/css">        body > span:nth-child(1) {            color: red;        }    </style></head><body>    <span>我是span1</span>    <span>我是span2</span>    <ul>        <li>            <ul><span>我是span3</span></ul>        </li>    </ul></body></html>

3. Sibling nodes

Sibling nodes are also easy to understand. It can be solved by using " " in css. You can see that I succeeded below Draw the second p in red.

<!DOCTYPE html><html xmlns="http://www.w3.org/1999/xhtml"><head>    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />    <title></title>    <style type="text/css">        .test + p {            color:red;        }    </style></head><body>    <p class="test">我是第一个段落</p>    <p>我是第二个段落</p></body></html>

4. Attribute selector

If you have played with jquery, I want to be very clear about this attribute selector. First, look at an example. I want to find name= Mark the p element of test in red.

<html xmlns="http://www.w3.org/1999/xhtml"><head>    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />    <title></title>    <style type="text/css">        p[name='test'] {            color: red;        }    </style>    <script src="Scripts/jquery-1.10.2.js"></script></head><body>    <p name="test">我是第一个段落</p>    <p>我是第二个段落</p></body></html>

Up to now, do you feel that the gameplay is exactly the same as jquery, and the feeling is getting stronger and stronger, and it has reached the realm of "you understand".

2: Speculation on the internal mechanism of CSS

As mentioned at the beginning of the article, the browser will apply the style of this tag to the "tag" specified in the dom based on the "tag" defined in the css. tag ", for example, I defined a

p style in CSS, but how can the browser find all the p elements in the dom? ? ? Because of the closed source, we cannot know its internal mechanism, but in jquery, we may have a glimpse

2, because the selector usage that can be displayed by css can be found in jquery. Then I can't wait to see how jquery extracts my various selector writing methods. Let's take a look at the source code.

<!DOCTYPE html><html xmlns="http://www.w3.org/1999/xhtml"><head>    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />    <title></title>    <style type="text/css">        p[name='test'] {            color: red;        }    </style>    <script src="Scripts/jquery-1.10.2.js"></script>    <script type="text/javascript">        $(document).ready(function () {            $("p[name='test']").hide();        });    </script></head><body>    <p name="test">我是第一个段落</p>    <p>我是第二个段落</p></body></html>

After searching in jquery, you can finally see that the native method of queryselectorAll is just called. You can also clearly see it in the console. Finally, The results of

are the found p elements. To verify, I opened a console under the taobao page.

Up to now, I have a rough guess, maybe at least under the chrome browser, the browser may also call the queryselectAll method in order to find the specified element in the dom. . .

Okay, that’s about it. Understanding the DOM model is the key, so that we can understand the subsequent rendering behavior of the browser.

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
HTML as a Markup Language: Its Function and PurposeHTML as a Markup Language: Its Function and PurposeApr 22, 2025 am 12:02 AM

The function of HTML is to define the structure and content of a web page, and its purpose is to provide a standardized way to display information. 1) HTML organizes various parts of the web page through tags and attributes, such as titles and paragraphs. 2) It supports the separation of content and performance and improves maintenance efficiency. 3) HTML is extensible, allowing custom tags to enhance SEO.

The Future of HTML, CSS, and JavaScript: Web Development TrendsThe Future of HTML, CSS, and JavaScript: Web Development TrendsApr 19, 2025 am 12:02 AM

The future trends of HTML are semantics and web components, the future trends of CSS are CSS-in-JS and CSSHoudini, and the future trends of JavaScript are WebAssembly and Serverless. 1. HTML semantics improve accessibility and SEO effects, and Web components improve development efficiency, but attention should be paid to browser compatibility. 2. CSS-in-JS enhances style management flexibility but may increase file size. CSSHoudini allows direct operation of CSS rendering. 3.WebAssembly optimizes browser application performance but has a steep learning curve, and Serverless simplifies development but requires optimization of cold start problems.

HTML: The Structure, CSS: The Style, JavaScript: The BehaviorHTML: The Structure, CSS: The Style, JavaScript: The BehaviorApr 18, 2025 am 12:09 AM

The roles of HTML, CSS and JavaScript in web development are: 1. HTML defines the web page structure, 2. CSS controls the web page style, and 3. JavaScript adds dynamic behavior. Together, they build the framework, aesthetics and interactivity of modern websites.

The Future of HTML: Evolution and Trends in Web DesignThe Future of HTML: Evolution and Trends in Web DesignApr 17, 2025 am 12:12 AM

The future of HTML is full of infinite possibilities. 1) New features and standards will include more semantic tags and the popularity of WebComponents. 2) The web design trend will continue to develop towards responsive and accessible design. 3) Performance optimization will improve the user experience through responsive image loading and lazy loading technologies.

HTML vs. CSS vs. JavaScript: A Comparative OverviewHTML vs. CSS vs. JavaScript: A Comparative OverviewApr 16, 2025 am 12:04 AM

The roles of HTML, CSS and JavaScript in web development are: HTML is responsible for content structure, CSS is responsible for style, and JavaScript is responsible for dynamic behavior. 1. HTML defines the web page structure and content through tags to ensure semantics. 2. CSS controls the web page style through selectors and attributes to make it beautiful and easy to read. 3. JavaScript controls web page behavior through scripts to achieve dynamic and interactive functions.

HTML: Is It a Programming Language or Something Else?HTML: Is It a Programming Language or Something Else?Apr 15, 2025 am 12:13 AM

HTMLisnotaprogramminglanguage;itisamarkuplanguage.1)HTMLstructuresandformatswebcontentusingtags.2)ItworkswithCSSforstylingandJavaScriptforinteractivity,enhancingwebdevelopment.

HTML: Building the Structure of Web PagesHTML: Building the Structure of Web PagesApr 14, 2025 am 12:14 AM

HTML is the cornerstone of building web page structure. 1. HTML defines the content structure and semantics, and uses, etc. tags. 2. Provide semantic markers, such as, etc., to improve SEO effect. 3. To realize user interaction through tags, pay attention to form verification. 4. Use advanced elements such as, combined with JavaScript to achieve dynamic effects. 5. Common errors include unclosed labels and unquoted attribute values, and verification tools are required. 6. Optimization strategies include reducing HTTP requests, compressing HTML, using semantic tags, etc.

From Text to Websites: The Power of HTMLFrom Text to Websites: The Power of HTMLApr 13, 2025 am 12:07 AM

HTML is a language used to build web pages, defining web page structure and content through tags and attributes. 1) HTML organizes document structure through tags, such as,. 2) The browser parses HTML to build the DOM and renders the web page. 3) New features of HTML5, such as, enhance multimedia functions. 4) Common errors include unclosed labels and unquoted attribute values. 5) Optimization suggestions include using semantic tags and reducing file size.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment