修改标签内容及字体颜色
利用遍历可实现对标签内容及颜色的更改:
let liTags = document.querySelectorAll('ul > li')
for (let i = 0; i < liTags.length; i++) {
liTags[i].classList.add('red')
}
for (let i = 0; i < liTags.length; i++) {
liTags[i].textContent = '修改'
}
封装函数
将上例代码封装成一个函数,代码如下:
function addClass(selector, classes) {
let nodes = document.querySelectorAll(selector)
for (let key in classes) {
let value = classes[key]
if (value) {
for (let i = 0; i < nodes.length; i++) {
nodes[i].classList.add(key)
}
} else {
for (let i = 0; i < nodes.length; i++) {
nodes[i].classList.remove(key)
}
}
}
}
function setText(selector, text) {
let nodes = document.querySelectorAll(selector)
for (let i = 0; i < nodes.length; i++) {
nodes[i].textContent = text
}
}
let classes = {
'red': true,
'green': false
}
addClass.call(undefined, 'ul>li', classes)
setText.call(undefined, 'ul>li', '封装函数')
添加命名空间
window.myDom = {
setClass: function(selector, classes) {
let nodes = document.querySelectorAll(selector)
for (let key in classes) {
let value = classes[key]
if (value) {
for (let i = 0; i < nodes.length; i++) {
nodes[i].classList.add(key)
}
} else {
for (let i = 0; i < nodes.length; i++) {
nodes[i].classList.remove(key)
}
}
}
},
setText: function(selector, text) {
let nodes = document.querySelectorAll(selector)
for (let i = 0; i < nodes.length; i++) {
nodes[i].textContent = text
}
}
}
myDom = window.myDom
let classes = {
'red': true,
'green': false
}
myDom.setClass.call(undefined, 'ul>li', classes)
myDom.setText.call(undefined, 'ul>li', '添加命名空间')
最后的完善
let jQuery = function(selector) {
let nodes = {}
if (selector) {
nodes = document.querySelectorAll(selector)
}
nodes.setClass = function(classes) {
for (let key in classes) {
let value = classes[key]
if (value) {
for (let i = 0; i < nodes.length; i++) {
nodes[i].classList.add(key)
}
} else {
for (let i = 0; i < nodes.length; i++) {
nodes[i].classList.remove(key)
}
}
}
}
nodes.setText = function(text) {
for (let i = 0; i < nodes.length; i++) {
nodes[i].textContent = text
}
}
return nodes
}
window.jQuery = jQuery
window.$ = jQuery
let classes = {
'red': true,
'green': true
}
let $liTags = $('ul>li')
$liTags.setClass.call($liTags, classes)
$liTags.setText.call($liTags, '完成')