基本选择器

基本选择器是jQuery中最常见的选择器,也是最简单的选择器,它是通过元素id,calss和标签名等来查找DOM元素,常见基本选择器分别有:

  • #id:根据给定的id匹配一个元素(单个元素)
  • .class:根据给定的类名匹配元素(元素集合)
  • element:根据给定的元素名匹配元素(元素集合)
  • *:匹配所有元素(元素集合)
  • selector1,selector2..:将每一个选择器匹配到的元素合并后一起返回

可以使用这些基本的选择器来完成绝大多数的工作,在开始前,我们先在html中写如下代码,后面所有的操作,都在此基础上完成。

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
  <script type="text/javascript" src="./jquery-3.2.1.js"></script>
  <style>
    .import{
      color:#fff;
      border:2px solid #303030;
    }
    .blue{
      200px;
      height:150px;
    }
  </style>
</head>
<body>
  <h2>基本选择器</h2>
  <input type="text" />
  <p>开始学习jquery</p>
  <div class="apple">today is Saturday</div>
</body>
</html>

基本选择器

1、ID选择器

$(function(){
  //ID选取
   $("#username").css("background-color",'lightblue');
   $("#username").css("color",'red');
})

基本选择器

通过id选择器,为id为username的元素添加了背景色和字体颜色,在JavaScript中用如下代码也可以实现相同相同。

window.onload = function(){
  document.getElementById('username').style.color = 'red';
  document.getElementById('username').style.backgroundColor = 'lightblue';
}

2、class选择器

$(function(){
   $(".apple").css('color','red');
   $(".apple").addClass("import blue");
   $(".apple").css({"font-size":"18px","font-weight":"bold","line-height":"150px"});
 })

基本选择器

在此需要注意的是,class类选择器和id选择器不同,得到的是元素组合,是一个伪数组,需要通过索引来获取具体的元素,在JavaScript中也可以实现上面的效果。

window.onload = function(){
    document.getElementsByClassName('apple')[0].style.color = 'blue';
    document.getElementsByClassName('apple')[0].className = 'import blue';
    document.getElementsByClassName('apple')[0].style.fontSize = '18px';
    document.getElementsByClassName('apple')[0].style.fontWeight = 'bold';
    document.getElementsByClassName('apple')[0].style.lineHeight = '150px';
}

3、元素名选择器

$(function(){
    $("p").css("border","5px solid green");
})

基本选择器

通过下面的JavaScript也能实现上面的效果。

 window.onload = function(){
       document.getElementsByTagName('p')[0].style.border = '5px solid green';
 }

4、通配符选择器

$(function(){
   $("*").css("background-color",'pink');
})

基本选择器

通配符选择器用来选择所有元素,在JavaScript中,有两种方式可以实现上面的效果。

Array.prototype.forEach.call(document.getElementsByTagName('*'),function(item,index,arr){
     item.style.backgroundColor = 'pink';
})
Array.prototype.forEach.call(document.all,function(item,index,arr){
     item.style.backgroundColor = 'pink';
})

5、联合选择器

$(function(){
 $("#username,.apple,p").css('background-color','orange');
        })

基本选择器

在JavaScript中可以通过如下方式实现上面的效果

Array.prototype.forEach.call(document.querySelectorAll('#username,.apple,p'),function(item,index,arr){
        item.style.color = 'red';
});