Home Web Front-end JS Tutorial JavaScript implements its own DOM selector principle and code_javascript skills

JavaScript implements its own DOM selector principle and code_javascript skills

May 16, 2016 pm 05:41 PM
dom Selector

Interpreter mode (Interpreter): Define a syntax format, execute it through program interpretation and complete corresponding tasks. In front-end programming scenarios, the interpreter mode can be applied to interpret CSS selectors to select DOM elements.

Open and closed principle: The open and closed principle in object-oriented is that a class or module should be open to extension and closed to modification. In this dom selector, the id selector and element selector are implemented. Class selector, if you need an attribute selector in the future, define an attribute selector to implement the corresponding method, and add the corresponding branch to create an attribute selector object in the simple factory.

Matching principle: Browsers match CSS selectors from right to left, so when implementing your own DOM selector, the matching behavior should be consistent with the native matching behavior of the browser. .

Code:

Copy code The code is as follows:

(function (ns) {
/*
//tagName
console.log(dom.get("p"));
//#id
console.log(dom.get("#div"));
//.class
console.log(dom.get(".span", document.body));
//tag.class
console.log(dom.get("div.span"));
//#id .class
console.log(dom.get("#div .span"));
//.class .class
console.log(dom.get(".ul .li-test"));
*/
var doc = document;
var simple = /^(?:#|.)?([w-_] )/;
function api(query, context) {
context = context || doc;
//调用原生选择器
if(!simple.test(query) && context.querySelectorAll){
return context.querySelectorAll(query);
}else {
//调用自定义选择器
return interpret(query, context);
}
}
//解释执行dom选择符
function interpret(query, context){
var parts = query.replace(/s /, " ").split(" ");
var part = parts.pop();
var selector = Factory.create(part);
var ret = selector.find(context);
return (parts[0] && ret[0]) ? filter(parts, ret) : ret;
}
//ID选择器
function IDSelector(id) {
this.id = id.substring(1);
}
IDSelector.prototype = {
find: function (context) {
return document.getElementById(this.id);
},
match: function(element){
return element.id == this.id;
}
};
IDSelector.test = function (selector) {
var regex = /^#([w-_] )/;
return regex.test(selector);
};
//元素选择器
function TagSelector(tagName) {
this.tagName = tagName.toUpperCase();
}
TagSelector.prototype = {
find: function (context) {
return context.getElementsByTagName(this.tagName);
},
match: function(element){
return this.tagName == element.tagName.toUpperCase() || this.tagName === "*";
}
};
TagSelector.test = function (selector) {
var regex = /^([w*-_] )/;
return regex.test(selector);
};
//类选择器
function ClassSelector(className) {
var splits = className.split('.');
this.tagName = splits[0] || undefined ;
this.className = splits[1];
}
ClassSelector.prototype = {
find: function (context) {
var elements;
var ret = [];
var tagName = this.tagName;
var className = this.className;
var selector = new TagSelector((tagName || "*"));
//支持原生getElementsByClassName
if (context.getElementsByClassName) {
elements = context.getElementsByClassName(className);
if(!tagName){
return elements;
}
for(var i=0,n=elements.length; iif( selector.match(elements[i]) ){
ret.push(elements[i]);
}
}
} else {
elements = selector.find(context);
for(var i=0, n=elements.length; iif( this.match(elements[i]) ) {
ret.push(elements[i]);
}
}
}
return ret;
},
match: function(element){
var className = this.className;
var regex = new RegExp("^|\s" className "$|\s");
return regex.test(element.className);
}
};
ClassSelector.test = function (selector) {
var regex = /^([w-_] )?.([w-_] )/;
return regex.test(selector);
};
//TODO:属性选择器
function AttributeSelector(attr){
this.find = function(context){
};
this.match = function(element){
};
}
AttributeSelector.test = function (selector){
var regex = /[([w-_] )(?:=([w-_] ))?]/;
return regex.test(selector);
};
//根据父级元素过滤
function filter(parts, nodeList){
var part = parts.pop();
var selector = Factory.create(part);
var ret = [];
var parent;
for(var i=0, n=nodeList.length; iparent = nodeList[i].parentNode;
while(parent && parent !== doc){
if(selector.match(parent)){
ret.push(nodeList[i]);
break;
}
parent = parent.parentNode;
}
}
return parts[0] && ret[0] ? filter(parts, ret) : ret;
}
//根据查询选择符创建相应选择器对象
var Factory = {
create: function (query) {
if (IDSelector.test(query)) {
return new IDSelector(query);
} else if (ClassSelector.test(query)) {
return new ClassSelector(query);
} else {
return new TagSelector(query);
}
}
};
ns.dom || (ns.dom = {});
ns.dom.get = api;
}(this));
Statement of this Website
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

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What are the ways to obtain DOM nodes in Vue3 What are the ways to obtain DOM nodes in Vue3 May 11, 2023 pm 04:55 PM

1. Native js gets the DOM node: document.querySelector (selector) document.getElementById (id selector) document.getElementsByClassName (class selector).... 2. Get the instance object of the current component in vue2: because each vue Each component instance contains a $refs object, which stores references to the corresponding DOM elements or components. So by default, the component's $refs point to an empty object. You can first add ref="name" to the component, and then pass this.$refs.

DOM manipulation guide in PHP DOM manipulation guide in PHP May 21, 2023 pm 04:01 PM

In web development, DOM (DocumentObjectModel) is a very important concept. It allows developers to easily modify and operate the HTML or XML document of a web page, such as adding, deleting, modifying elements, etc. The built-in DOM operation library in PHP also provides developers with rich functions. This article will introduce the DOM operation guide in PHP, hoping to help everyone. The basic concept of DOM DOM is a cross-platform, language-independent API that can

Use the :nth-child(n+3) pseudo-class selector to select the style of child elements whose position is greater than or equal to 3 Use the :nth-child(n+3) pseudo-class selector to select the style of child elements whose position is greater than or equal to 3 Nov 20, 2023 am 11:20 AM

Use the :nth-child(n+3) pseudo-class selector to select the style of child elements whose position is greater than or equal to 3. The specific code example is as follows: HTML code: <divid="container"><divclass="item"&gt ;First child element</div><divclass="item"&

What to do if the javascript selector fails What to do if the javascript selector fails Feb 10, 2023 am 10:15 AM

The JavaScript selector fails because the code is not standardized. The solution is: 1. Remove the imported JS code and the ID selector method will be effective; 2. Just introduce the specified JS code before introducing "jquery.js".

What is the reason why ref binding to dom or component fails in vue3 and how to solve it What is the reason why ref binding to dom or component fails in vue3 and how to solve it May 12, 2023 pm 01:28 PM

Vue3ref binding DOM or component failure reason analysis scenario description In Vue3, it is often used to use ref to bind components or DOM elements. Many times, ref is clearly used to bind related components, but ref binding often fails. Examples of ref binding failure situations The vast majority of cases where ref binding fails is that when the ref is bound to the component, the component has not yet been rendered, so the binding fails. Or the component is not rendered at the beginning and the ref is not bound. When the component starts to render, the ref also starts to be bound, but the binding between ref and the component is not completed. At this time, problems will occur when using component-related methods. The component bound to ref uses v-if, or its parent component uses v-if to cause the page to

From beginner to proficient: Master the skills of using is and where selectors From beginner to proficient: Master the skills of using is and where selectors Sep 08, 2023 am 09:15 AM

From beginner to proficient: Master the skills of using is and where selectors Introduction: In the process of data processing and analysis, the selector is a very important tool. Through selectors, we can extract the required data from the data set according to specific conditions. This article will introduce the usage skills of is and where selectors to help readers quickly master the powerful functions of these two selectors. 1. Use of the is selector The is selector is a basic selector that allows us to select the data set based on given conditions.

What are the dom and bom objects? What are the dom and bom objects? Nov 13, 2023 am 10:52 AM

There are 5 DOM objects including "document", "element", "Node", "Event" and "Window"; 2. "window", "navigator", "location" and "history" and "screen" and other 5 BOM objects.

What is the difference between bom and dom What is the difference between bom and dom Nov 13, 2023 pm 03:23 PM

BOM and DOM are different in terms of role and function, relationship with JavaScript, interdependence, compatibility of different browsers, and security considerations. Detailed introduction: 1. Role and function. The main function of BOM is to operate the browser window. It provides direct access and control of the browser window. The main function of DOM is to convert the web document into an object tree, allowing developers to Use this object tree to obtain and modify the elements and content of the web page; 2. Relationship with JavaScript, etc.

See all articles