自己实现三个API(getSiblings,addCLass,text)

235 阅读2分钟
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>JS Bin</title>
</head>
<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>
</html>
window.myAPI = function(nodeOrSelector){
    let nodes;
    //如果传进来的是字符串(选择器)则返回一个伪数组
    if(typeof nodeOrSelector === 'string'){
        nodes = document.querySelectorAll(nodeOrSelector)  //伪数组(一致性)
    }//如果传进来的是一个节点则直接将该节点赋给nodes
    else if(nodeOrSelector instanceof Node){
        nodes = {                                          //伪数组(一致性)
            0: nodeOrselector,
            length:1
        }
    }
    //为选择器对应的所有元素添加类
    nodes.addClass = function(value){
        for(let i=0; i<nodes.length; i++){
            nodes[i].classList.add(value);
        }
    }
    //来吧,我的兄弟们
    nodes.getSiblings = function () {
        var allChildren = nodes[0].parentNode.children;
        var array = {
            length: 0
        }
        for (let i = 0; i < allChildren.length; i++)
            if (allChildren[i] !== nodes[0]) {
                array[array.length] = allChildren[i];  //不能用array[i]哦,这样长度就不对了
                array.length += 1;
        }
        return array;
  }
    //注意两个判断语句的区别哦~~
    nodes.text = function(value){
        if(typeof value === 'string'){     //如果传入了字符串则覆盖当前选择器对应的内容
            for(let i=0; i<nodes.length; i++){
                nodes[i].textContent = value;
            }
        }else if(value === undefined){    //如果没传值则获取当前选择器对应的内容
            var array = [];
            for(let i=0; i<nodes.length; i++){
                array.push(nodes[i].textContent)
            }
            return array;
        }
    }
    return nodes;
}

附:

  1. textContent 会获取所有元素的内容,包括 < script> < style> 元素,然而 innerText 不会。
  2. innerText 受 CSS 样式的影响,并且不会返回隐藏元素的文本,而textContent会。 由于 innerText 受 CSS 样式的影响,它会触发重排(reflow),但textContent 不会。
  3. 与 textContent 不同的是, 在 Internet Explorer (对于小于等于 IE11 的版本) 中对 innerText 进行修改, 不仅会移除当前元素的子节点,而且还会永久性地破坏所有后代文本节点(所以不可能再次将节点再次插入到任何其他元素或同一元素中)。
  4. 摘抄自MDN