zoukankan      html  css  js  c++  java
  • JavaScript,DOM之 querySelect() 和 querySelectAll()

    querySelect() 

    这个比较简单和直接,给几个例子即可了解

    获取文档中 class="example" 的第一个元素:
    
    document.querySelector(".example");
    获取文档中第一个 <p> 元素:
    
    document.querySelector("p");
    假定你选择了两个选择器: <h2><h3> 元素。
    
    以下代码将为文档的第一个 <h2> 元素添加背景颜色,因为我们只能从上到下筛选出第一个 存在于筛选器中的标签:
    
    <h2>A h2 element</h2>
    <h3>A h3 element</h3>
    
    document.querySelector("h2, h3").style.backgroundColor = "red";
    获取文档中 class="example" 的第一个 <p> 元素:
    
    document.querySelector("p.example");

    querySelectAll() 

    这个顾名思义,是筛选出所有符合条件的标签。生成一个    NodeList (节点列表) , 我们可以懒惰的通过下标进行访问。

    // 获取文档中所有的 <p> 元素
    var x = document.querySelectorAll("p"); 
     
    // 设置第一个 <p> 元素的背景颜色
    x[0].style.backgroundColor = "red";
    // 获取文档中所有 class="example" 的 <p> 元素
    var x = document.querySelectorAll("p.example"); 
     
    // 设置 class="example" 的第一个 <p> 元素的背景颜色
    x[0].style.backgroundColor = "red";
    获取文档中有 "target" 属性的第一个 <a> 元素:
    
    document.querySelector("a[target]");
    计算文档中 class="example" 的 <p> 元素的数量(使用 NodeList 对象的 length 属性):
    
    var len = document.querySelectorAll(".example").length;
    var x = document.querySelectorAll(".example");
    var i;
    for (i = 0; i < x.length; i++) {
        x[i].style.backgroundColor = "red";
    }
    var x = document.querySelectorAll("div > p");
    var i;
    for (i = 0; i < x.length; i++) {
        x[i].style.backgroundColor = "red";
    }

      经过了上面的阅读,我们发现,实际上 selector  最重要的就是括号内那部分,即 我们怎样编写选择器决定了我们筛选出来的内容是什么。

    所以这里有一个   CSS选择器网站,可供参考

  • 相关阅读:
    Zookeeper zkCli.sh常用命令
    windows 服务
    Zookeeper的下载安装
    Zookeeper 基础知识
    在Java中使用Redis
    Redis 集群(cluster)
    Redis 哨兵(Sentinel)机制
    Redis 主从复制
    Redis 发布/订阅
    Redis 事务
  • 原文地址:https://www.cnblogs.com/3532gll/p/9538271.html
Copyright © 2011-2022 走看看