


JavaScript implements its own DOM selector principle and code_javascript skills
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:
(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; i
ret.push(elements[i]);
}
}
} else {
elements = selector.find(context);
for(var i=0, n=elements.length; 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; i
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));

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

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.

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. The specific code example is as follows: HTML code: <divid="container"><divclass="item"> ;First child element</div><divclass="item"&

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".

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 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.

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.

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.
