jQuery selector (2) basic selector + hierarchical selector

1: Get all the <p>elements, <p>continue to loop on the elements, because the array objects are obtained, <p>add behavior events to each element

var items=document.getElementsByTagName("p");
for(var i=0;i<items.length;i++){
    items[i].onclick=function(){
     //do something 
  }
}

2: Get the table according to the table id, get the element in the table, get <tbody>the <tbody>element under the <tr>element, output the acquired element in a loop <tr>, divide the index value of the element by 2 and take the modulo, and then set different background colors according to the parity.

var item=docuement.getElementById("tb");
var tbody=item.getElementsByTagName("tbody")[0];
var trs=tbody.getElementByTagName("tr");
for(var i=0;i<trs.length;i++){
   if(i%2==0){
      trs[i].style.backgroundColor="#888";
   }
}

3: Create an empty array, get all the check boxes with the name "check", loop to determine whether the check boxes are selected, if they are selected, add them to the array, get the output button, and then add an onclick event to the button to output the array length.

var btn=document.getElementById("btn");
btn.onclick=function(){
   var array=new Array();
   var items=document.getElementsByName("check");

   for(i=0;i<items.length;i++){
     if(items[i].checked){
        array.push(items[i].value);
     }
  }
  alert(array.length);  
}

Basic selector:

#id  $("#test")选取id为test的元素
.class $(".test")选取所有classtest的元素
element  $("p")选取所有的<p>元素

$("div,span,p.myClass") 选取所有的<div>,<span>和拥有classmyClass<p>标签的一组元素

Hierarchy selector:

$("ancestor  descendant")  $("div span")选取<div>里面所有的<span>元素

$("parent>child")  $("div >span")选取<div>元素下元素名为<span>的子元素

$("prev+next") $(".one+div")选取classone的下一个<div>同辈元素

$("#two~div")选取id为two的元素后面的所有<div>同辈元素

后面两个用得少,因为在jQuery里可以用更加简单的方法代替
$(".one+div")  $(".one").next("div");

$("prev~div")  $("#prev").nextAll("div");

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325200454&siteId=291194637