


Encapsulates a function that can obtain the text content of an element
This time I will introduce to you the encapsulation of a function that can obtain the text content of an element. What are the precautions for encapsulating a function that can obtain the text content of an element? The following is a practical case, let's take a look. A.1 Logical steps
Goal: Get all sibling element nodes of an element
S1 Get the parent element node of an element and all its child nodes
S2 Statement The pseudo array object to be returnedS3 Remove the element node passed in by itself
S4 Use array.length to pass in the array content by subscript (if i is used, it is possible to skip it, and it is not in order )
S5 Return this pseudo array
A.1 Specific code
<body> <ul> <li id="item1">选项1</li> <li id="item2">选项2</li> <li id="item3">选项3</li> <li id="item4">选项4</li> <li id="item5">选项5</li> </ul> </body>
//S5 封装为函数(API) function getSiblings(node){ var allChildren = node.parentNode.children; //S1 获取li的父元素节点 + 其所有子节点 var array = {length:0}; //S2 声明将要返回的伪数组对象 for (let i = 0; i < allChildren.length; i++){ if (allChildren[i] !== node){ // S3 去除本身传入的元素节点 array[array.length] = allChildren[i]; // S4 利用 array.length按下标传入数组内容(如果用i,i是有可能跳过的,就不是按序了) array.length += 1; } } // console.log(array); // {0:li#item1, 1:li#item2......} return array; // S6 返回这个伪数组 }
A.2 Logical steps
Goal: Add/remove class names to elements in batches
S1
Traverse the key value of the objectS2 When the value of the class name is true, add the class name; otherwise, remove it
A.2 Specific code
function addClass(node, classes){ // var classes = {'a':true, 'b':false, 'c':true} //S1 构造要传入的类名对象 for (let key in classes){ //S2 遍历对象的key值 value = classes[key]; // if (value){ //S3 当类名的值为ture时,添加类名 // node.classList.add(key); // }else{ // node.classList.remove(key); // } // 以上 if/else可以优化为 var methodName = value ? 'add':'remove'; node.classList[methodName](key); } }
B Add the
namespace, which is window.mydom = {};
mydom.getSiblings = function getSiblings(node){
var allChildren = node.parentNode.children;
var array = {length:0};
for (let i = 0; i < allChildren.length; i++){
if (allChildren[i] !== node){ // 去除本身传入的元素节点
array[array.length] = allChildren[i];
array.length += 1;
}
}
return array;
}
mydom.addClass = function addClass(node, classes){
classes.forEach( (value)=> node.classList.add(value) );
}
Copy after login`The calling method is mydom.getSiblings(item3); mydom.addClass(item3, [' a','b'])
The desired calling method is
item3.getSibling() / item3.addClass('['a', 'b'])
C.1 this prototype chain
Node.prototype.getSiblings = function getSiblings(){
var allChildren = this.parentNode.children;
var array = {length:0};
for (let i = 0; i < allChildren.length; i++){
if (allChildren[i] !== this){ // 去除本身传入的元素节点
array[array.length] = allChildren[i];
array.length += 1;
}
}
return array;
}
Node.prototype.addClass = function addClass(classes){
classes.forEach( (value)=> this.classList.add(value) );
}
// 参考效果
console.log( item3.getSiblings() )
Copy after login
C.2 node2 function_object mode
window.Node2 = function(node){ //要挂载到全局window上,才能直接访问
return {
getSiblings: function(){
var allChildren = node.parentNode.children;
var array = {length:0};
for (let i = 0 ; i < allChildren.length; i++){
if (allChildren[i] !== node){
array[array.length] = allChildren[i];
arrat.length += 1;
}
}
return array;
},
addClass: function(classes){
classes.forEach( (value) => node.classList.add(value) )
}
}
}
//参考效果
node2 = Node2(item3);
console.log( node2.getSibling() );
node2.addClass( ['a', 'b', 'c'] )
Copy after login
C.3 Simulate a simplified jQuery
window.jQuery = function(nodeOrSelector){
let node;
if (typeof nodeOrSelector === 'string'){ //类型检测
node = document.querySelector(nodeOrSelector); //只支持返回一个节点
} else {
node = nodeOrSelector;
}
return{
getSibligs: function(){
var allChildren = node.parentNode.children;
var array = {length:0};
for (let i = 0 ; i < allChildren.length; i++){
if (allChildren[i] !== node){
array[array.length] = allChildren[i];
arrat.length += 1;
}
}
return array;
},
addClass: function(classes){
classes.forEach( (value) => node.classList.add(value) )
}
}
}
//调用效果
var node2 = jQuery('#item3');
node2.getSibling();
node2.addClass(['red', 'c'])
Copy after login
C.4 Support Pass in one/multiple nodes
window.jQuery = function(nodeOrSelector){
let nodes = {}; //S1 以后要用到的元素节点伪数组,空对象
if (typeof nodeOrSelector === 'string'){
let temp = document.querySelectorAll(nodeOrSelector)//S2元素节点伪数组
for (let i = 0 ; i < temp.length; i++){
nodes[i]= temp[i]; //S3 去除多余原型链部分
}
nodes.length = temp.length;
} else if (nodeOrSelector instanceof Node){
nodes ={ 0: nodeOrSelector , length:1}; //S4 单个元素也要返回伪数组
}
nodes.addClass = function(classes){
// for (let i = 0; i < nodes.length; i++){
// classes.forEach( (value) => nodes[i].classList.add(value) );
// }
// 更好的写法是
classes.forEach( (value) => {
for (let i=0; i<nodes.length; i++){
nodes[i].classList.add(value);
}
})
}
return nodes
}
//调用效果
var node2 = jQuery('ul>li');
node2.addClass( ['blue'] );
Copy after login
D Add other functions
window.jQuery = function(nodeOrSelector){
let nodes = {}; //S1 以后要用到的元素节点伪数组,空对象
if (typeof nodeOrSelector === 'string'){
let temp = document.querySelectorAll(nodeOrSelector)//S2元素节点伪数组
for (let i = 0 ; i < temp.length; i++){
nodes[i]= temp[i]; //S3 去除多余原型链部分
}
nodes.length = temp.length;
} else if (nodeOrSelector instanceof Node){
nodes ={ 0: nodeOrSelector , length:1}; //S4 单个元素也要返回伪数组
}
nodes.addClass = function(classes){
// 更好的写法是
classes.forEach( (value) => {
for (let i=0; i<nodes.length; i++){
nodes[i].classList.add(value);
}
})
}
// 获取元素节点文本内容
// S1 遍历元素节点的伪数组;
// S2 获取其文本内容,并推送到存储的 数组;
// S3 返回数组
nodes.getText = function(){
var texts = [];
for (i = 0; i < nodes.length; i++){
texts.push(nodes[i].textContent); //获取元素节点内容并推入到数组
}
return texts
}
// 设置元素节点文本内容
// S1 遍历元素节点的伪数组;
// S2 设置其文本内容为传入的参数内容
nodes.setText = function(text){
for (i = 0 ; i < nodes.length; i++){
nodes[i].textContent = text;
}
}
// 合并为一个接口
// S1 判断是否传入了参数, 传入了就是设置,没传入就是读取
nodes.text = function(text){
if (text === undefined){
var texts = [];
for (i = 0; i < nodes.length; i++){
texts.push(nodes[i].textContent);
}
return texts
} else {
for (i = 0 ; i < nodes.length; i++){
nodes[i].textContent = text;
}
}
}
return nodes
}
// 调用结果
var node2 = jQuery('ul>li');
node2.addClass( ['blue'] );
// 获取文本内容
// var text = node2.text();
// console.log(text);
// 设置文本内容
node2.text('hi');
Copy after login
I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the PHP Chinese website!
Recommended reading:
Detailed explanation of the use of array prototype methods in jsPractical use of EasyCanvas drawing library in Pixeler project development SummarizeThe above is the detailed content of Encapsulates a function that can obtain the text content of an element. For more information, please follow other related articles on the PHP Chinese website!
window.mydom = {}; mydom.getSiblings = function getSiblings(node){ var allChildren = node.parentNode.children; var array = {length:0}; for (let i = 0; i < allChildren.length; i++){ if (allChildren[i] !== node){ // 去除本身传入的元素节点 array[array.length] = allChildren[i]; array.length += 1; } } return array; } mydom.addClass = function addClass(node, classes){ classes.forEach( (value)=> node.classList.add(value) ); }
The desired calling method is
item3.getSibling() / item3.addClass('['a', 'b'])
C.1 this prototype chainNode.prototype.getSiblings = function getSiblings(){ var allChildren = this.parentNode.children; var array = {length:0}; for (let i = 0; i < allChildren.length; i++){ if (allChildren[i] !== this){ // 去除本身传入的元素节点 array[array.length] = allChildren[i]; array.length += 1; } } return array; } Node.prototype.addClass = function addClass(classes){ classes.forEach( (value)=> this.classList.add(value) ); } // 参考效果 console.log( item3.getSiblings() )
window.Node2 = function(node){ //要挂载到全局window上,才能直接访问 return { getSiblings: function(){ var allChildren = node.parentNode.children; var array = {length:0}; for (let i = 0 ; i < allChildren.length; i++){ if (allChildren[i] !== node){ array[array.length] = allChildren[i]; arrat.length += 1; } } return array; }, addClass: function(classes){ classes.forEach( (value) => node.classList.add(value) ) } } } //参考效果 node2 = Node2(item3); console.log( node2.getSibling() ); node2.addClass( ['a', 'b', 'c'] )
window.jQuery = function(nodeOrSelector){ let node; if (typeof nodeOrSelector === 'string'){ //类型检测 node = document.querySelector(nodeOrSelector); //只支持返回一个节点 } else { node = nodeOrSelector; } return{ getSibligs: function(){ var allChildren = node.parentNode.children; var array = {length:0}; for (let i = 0 ; i < allChildren.length; i++){ if (allChildren[i] !== node){ array[array.length] = allChildren[i]; arrat.length += 1; } } return array; }, addClass: function(classes){ classes.forEach( (value) => node.classList.add(value) ) } } } //调用效果 var node2 = jQuery('#item3'); node2.getSibling(); node2.addClass(['red', 'c'])
window.jQuery = function(nodeOrSelector){ let nodes = {}; //S1 以后要用到的元素节点伪数组,空对象 if (typeof nodeOrSelector === 'string'){ let temp = document.querySelectorAll(nodeOrSelector)//S2元素节点伪数组 for (let i = 0 ; i < temp.length; i++){ nodes[i]= temp[i]; //S3 去除多余原型链部分 } nodes.length = temp.length; } else if (nodeOrSelector instanceof Node){ nodes ={ 0: nodeOrSelector , length:1}; //S4 单个元素也要返回伪数组 } nodes.addClass = function(classes){ // for (let i = 0; i < nodes.length; i++){ // classes.forEach( (value) => nodes[i].classList.add(value) ); // } // 更好的写法是 classes.forEach( (value) => { for (let i=0; i<nodes.length; i++){ nodes[i].classList.add(value); } }) } return nodes } //调用效果 var node2 = jQuery('ul>li'); node2.addClass( ['blue'] );
window.jQuery = function(nodeOrSelector){ let nodes = {}; //S1 以后要用到的元素节点伪数组,空对象 if (typeof nodeOrSelector === 'string'){ let temp = document.querySelectorAll(nodeOrSelector)//S2元素节点伪数组 for (let i = 0 ; i < temp.length; i++){ nodes[i]= temp[i]; //S3 去除多余原型链部分 } nodes.length = temp.length; } else if (nodeOrSelector instanceof Node){ nodes ={ 0: nodeOrSelector , length:1}; //S4 单个元素也要返回伪数组 } nodes.addClass = function(classes){ // 更好的写法是 classes.forEach( (value) => { for (let i=0; i<nodes.length; i++){ nodes[i].classList.add(value); } }) } // 获取元素节点文本内容 // S1 遍历元素节点的伪数组; // S2 获取其文本内容,并推送到存储的 数组; // S3 返回数组 nodes.getText = function(){ var texts = []; for (i = 0; i < nodes.length; i++){ texts.push(nodes[i].textContent); //获取元素节点内容并推入到数组 } return texts } // 设置元素节点文本内容 // S1 遍历元素节点的伪数组; // S2 设置其文本内容为传入的参数内容 nodes.setText = function(text){ for (i = 0 ; i < nodes.length; i++){ nodes[i].textContent = text; } } // 合并为一个接口 // S1 判断是否传入了参数, 传入了就是设置,没传入就是读取 nodes.text = function(text){ if (text === undefined){ var texts = []; for (i = 0; i < nodes.length; i++){ texts.push(nodes[i].textContent); } return texts } else { for (i = 0 ; i < nodes.length; i++){ nodes[i].textContent = text; } } } return nodes } // 调用结果 var node2 = jQuery('ul>li'); node2.addClass( ['blue'] ); // 获取文本内容 // var text = node2.text(); // console.log(text); // 设置文本内容 node2.text('hi');

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

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

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

Google Authenticator is a tool used to protect the security of user accounts, and its key is important information used to generate dynamic verification codes. If you forget the key of Google Authenticator and can only verify it through the security code, then the editor of this website will bring you a detailed introduction on where to get the Google security code. I hope it can help you. If you want to know more Users please continue reading below! First open the phone settings and enter the settings page. Scroll down the page and find Google. Go to the Google page and click on Google Account. Enter the account page and click View under the verification code. Enter your password or use your fingerprint to verify your identity. Obtain a Google security code and use the security code to verify your Google identity.

Can downloads be deleted? In recent years, with the advent of the digital age, more and more digital products and services have appeared in our lives. What follows is that our demand for digital content is increasing day by day. In our daily life and work, we often need to download a variety of files, such as documents, pictures, audios, videos, etc. These downloaded files are usually saved in a folder called "downloads". However, over time we often find that,"

What games can be played with i34150 with 1G independent graphics? Can it play small games such as LoL? GTX750 and GTX750TI are very suitable graphics card choices. If you just play some small games or not play games, it is recommended to use the i34150 integrated graphics card. Generally speaking, the price difference between graphics cards and processors is not very big, so it is important to choose a reasonable combination. If you need 2G of video memory, it is recommended to choose GTX750TI; if you only need 1G of video memory, just choose GTX750. GTX750TI can be seen as an enhanced version of GTX750, with overclocking capabilities. Which graphics card can be paired with i34150 depends on your needs. If you plan to play stand-alone games, it is recommended that you consider changing the graphics card. you can choose

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

If the "Get the latest updates as soon as they become available" option is missing or grayed out, you may be running a Developer Channel Windows 11 build, and this is normal. For others, issues arise after installing the KB5026446 (22621.1778) update. Here's what you can do to get back the "Get the latest updates as soon as they become available" option. How do I get the "Get the latest updates as soon as they're available" option back? Before starting any of the solutions below, make sure to check for the latest Windows 11 updates and install them. 1. Use ViVeTool to go to the Microsoft Update Catalog page and look for the KB5026446 update. Download and reinstall the update on your PC

Although the general operations of domestic mobile phones are very similar, there are still some differences in some details. For example, different mobile phone models and manufacturers may have different dual-SIM installation methods. Erzhenwo 12Pro, a new mobile phone, also supports dual-SIM dual standby, but how should dual-SIM be installed on this phone? How to install dual SIM on Realme 12Pro? Remember to turn off your phone before installation. Step 1: Find the SIM card tray: Find the SIM card tray of the phone. Usually, in the Realme 12 Pro, the SIM card tray is located on the side or top of the phone. Step 2: Insert the first SIM card. Use a dedicated SIM card pin or a small object to insert it into the slot in the SIM card tray. Then, carefully insert the first SIM card.

jQuery Tips: How to Quickly Obtain Screen Height In web development, you often encounter situations where you need to obtain the screen height, such as implementing responsive layout, dynamically calculating element size, etc. Using jQuery, you can easily achieve the function of obtaining the screen height. Next, we will introduce some implementation methods of using jQuery to quickly obtain the screen height, and attach specific code examples. Method 1: Use jQuery's height() method to obtain the screen height. By using jQuery's height

CSS transition effect: How to achieve the sliding effect of elements Introduction: In web design, the dynamic effect of elements can improve the user experience, among which the sliding effect is a common and popular transition effect. Through the transition property of CSS, we can easily achieve the sliding animation effect of elements. This article will introduce how to use CSS transition properties to achieve the sliding effect of elements, and provide specific code examples to help readers better understand and apply. 1. Introduction to CSS transition attribute transition CSS transition attribute tra
