Chapter four :JQuery Selectors

1.Jquery Introduction to selectors

(1) Jquery The selector in inherits completely CSS Style , utilize Jquery Selectors , It's very convenient and fast to find specific Dom Elements , And then add behaviors to them , There's no need to worry about whether the browser supports this selector , Learning to use selectors is learning Jqeury The basis of ,Jquery All of the behavior rules must be valid after getting the element .

2.jquery The advantages of selectors

(1) Simple writing ,$() function

(2) Support CSS1 To CSS3 Selectors

(3) Perfect processing mechanism

3. Selector classification

(1) Basic selector : Through elements id,class And tag names to find Dom Elements

  1)$("#id") According to the given ID Match an element , Return single element   $("#name") selection Id by test The elements of

2)$(".class") Match elements based on given class name Return collection elements   $(".class") Select all class by class The elements of

3)$("element") Match the element... According to the given element name , Return collection elements   $("input") Pick all input Elements

4)$("*") Match all elements , Return collection elements ,$("*") Pick all the elements

5)$("selector1,selector2,...,selectorN") Merge the elements matched by each selector and return the set elements , $("div,span,p.myClass") Select all <div>,<span> And have class by myClass Of <p> A set of elements of a label

Import files :

jQ library :



<script type="text/javascript" src="jq/jQuery1.11.1.js"></script>
<script type="text/javascript">
$("span").css("background","pink ");
}); $(function(){
$("body span").css("background","#6FF");
}); </script>
</head> <body>
<h2> Spirited away </h2>
<p><span> Alias :</span> Shadow girl </p>
<p><span> The director :</span> Hayao Miyazaki </p>
<p><span> brief introduction </span></p>
<p><span> Chihiro </span> Drive to your new home with mom and dad , In the outskirts of the road inadvertently into the mysterious Tunnel -- They went to another secret world ...<span> >> detailed </span></p>
<a href="#"> Play immediately </a><strong><a href="#"> Play it fast </a></strong> <span> Download and watch </span>

(2) Hierarchy selector : If you want to pass Dom The hierarchical relationship between elements to get specific elements , For example, offspring elements , Subelement , Adjacent elements and peer elements

1)$("ancestor descendant") get ancestor Everything in the element descendant( Progeny ) Elements ,$("div span") selection <div> All of them <span> Elements

2)$("parent>child") selection parent Under the element child( Son ) Elements , Return collection elements $("div span") selection <div> The element under the element is called <span> Child elements

annotation : and $("ancestor descendant") There's a difference ,$("ancestor descendant") It's the descendant element that's chosen

3)$("prev+next") The selection follows prev Elemental next Elements , Return collection elements ,$(".one+div") selection class by one Next <div> Peer elements

4)$("prev~siblings") selection prev Everything after the element siblings Elements ,$("#two~div") selection Id by two All of the following elements of <div> Peer elements

annotation : have access to next() To replace $('prev+next') Selectors   $(".one").next("div"); have access to nextAll() To replace $("prev~siblings") Selectors $("#two").nextAll(div)

(3) Filter selector : Mainly through specific filtering rules to filter out the needed Dom Elements , According to different filtering rules , Filter selector can be divided into basic filter , Content filtering , Visibility filtering , Property filter , Sub element filtering and form object attribute filtering selectors

1) Basic filter selector

1)$(":first") Pick the first element ,$("div:first") Select all <div> The first of the elements <div> Elements .

2)$(":last") Pick the last element ,$("div:last") Select all <div> The last of the elements <div> Elements .

3)$(":not(selector)") Remove all elements that match the given selector ,$("input:not(.myClass)") selection class No myClass Of <input> Elements .

4)$(":even") Pick all elements whose index is even , Index from 0 Start ,$("input:even") The selection index is even <input> Elements

5)$(":odd") Pick all elements whose index is odd , Index from 0 Start ,$("input:odd") The selection index is odd <input> Elements

6)$(":eq(index)") The selection index is equal to index The elements of ,(index from 0 Start ),$("input:eq(1)") The selection index is equal to 1 Of <input> Elements

7)$(":gt(index)") The selection index is greater than index The elements of ,(index from 0 Start ),$("input:gt(1)") The selection index is greater than 1 Of <input> Elements ( Greater than 1, And do not include 1)

8)$(":lt(index)") The selection index is less than index The elements of ,(index from 0 Start ),$("input:lt(1)") The selection index is less than 1 Of <input> Elements ( Less than 1, And do not include 1)

9)$(":header") Select all Title Elements , for example :h1,h2,h3 wait ,$(":header") Select all of the <h1>,<h2>,<h3>...

10)$(":animated") Select all the elements that are currently animating ,$("div:animated") Select the <div> Elements .

11)$(":focus") Select the currently focused element ,$(":focus") Select the currently focused element

2) Content filter selector : It is mainly reflected in the sub elements or text content it contains

1)$(":contains(text)") Select the text as "text" The elements of ,$("div:contains(' I ')") Selection contains text " I " Of <div> Elements

2)$(":empty") Select an empty element that does not contain child elements or text ,$("div:empty") Select no child elements ( Include text elements ) Of <div> Empty elements

3)$(":has(selector)") Select the element that contains the element that the selector matches ,$("div:has(p)") Choose to include <p> Elemental <div> Elements

4)$(":parent") Select elements that contain children or text ,$("div:parent") Select have child elements ( Include text elements ) Of <div> Elements

eg: Filter selector :

<script type="text/javascript" src="jq/jQuery1.11.1.js"></script>
<script type="text/javascript">
}); </script>
</head> <body>
<h2> Network novel </h2>
<li> Wang Ji is not easy to be </li>
<li> Fatal trade </li>
<li class="three"> Jialan temple </li>
<li> Spring against the sky </li>
<li> Love in time </li>
<li> Zhang Zhengui's story </li>
<li> First intimate contact </li>

3) Visibility filter selector : Select the elements according to their visible and invisible states

1)$(":hidden") Pick all the invisible elements ,$(":hidden") Pick all the invisible elements , Include <input type="hidden" />,

<div style="display:none;"> and <div style="visibility:hidden;"> Equal elements . If you just want to select <input> Elements , have access to $("input:hidden")

2)$(":visible") Select all visible elements ,$("div:visible") Select all visible <div> Elements

4) Property filter selector : Get the corresponding element through the attribute of the element

1)$("[attribute]") Select the element with this attribute ,$("div[id]") Select owned properties Id Of <idv> Elements .

2)$("[attribute=value]") The value of the selected property is value The elements of ,$("div[title=test]") Select Properties title by "test" Of <div> Elements

3)$("[attribute!=value]") The value of the selected property is not equal to value The elements of ,$("div[title!=test]") Select Properties title It's not equal to "test" Of <div> Elements ( Be careful : There is no attribute title Of <div> Elements will also be selected )

4)$("[attribute^=value]") Select the attribute directly with value The starting element ,$("div[title^=test]") Select Properties title With "test" At the beginning <div> Elements

5)$("[attribute$=value]") Select the value of the property to value The ending element ,$("div[title$=test]") Select Properties title With "test" The end of the <div> Elements

6)$("[attribute*=value]") The value of the selected property contains value The elements of ,$("div[title*=test]") Select Properties title contain "test" Of <div> Elements

7)$("[attribute|=value]") Select a property that is equal to or prefixed with a given string ( The string is followed by a hyphen "-") The elements of ,$("div[title|="en"]") Select Properties title be equal to en Or with en The prefix ( Give a string followed by a "-") The elements of

8)$("[attribute~=value]") Select a value separated by a space for the attribute that contains a given value element ,$("div[title~='uk']") Select Properties title Values separated by spaces contain characters uk The elements of

9)$("[attribute1][attribute2][attribute3]") Combine attribute selectors into a composite attribute selector , Satisfy multiple conditions , Every time you choose , Narrow down once

$("div[id][title$='test']") Select owned properties id, And properties title With "test" The end of the <div> Elements

eg: Attribute selector :

 <script type="text/javascript" src="jq/jQuery1.11.1.js"></script>
<script type="text/javascript">
// Change the color of the meter
}); // Change odd colors
}); // change id Not for box The element background color of
}); // Change to h The color of the beginning element
}); // Change to jp The color of the ending element
}); // Change contains s The color of the elements
}); // Change contains class attribute , And title The value of the property contains y Of <li> The color of the elements
<style type="text/css">
#box {background-color:#FFF;border:2px solid #000;height:230px;width:200px;padding:5px;}
</head> <body>
<div id="box">
<h2 class="odds" title="cartoonlist"> Animation list </h2>
<li class="odds" title="kn_jp"> Detective Conan </li>
<li class="evens" title="hy_jp"> naruto </li>
<li class="odds" title="ki_jp"> A god of death </li>
<li class="enens" title="ko_jp"> Fairy Tail </li>
<li class="odds" title="ht_jp"> Gin Tama </li>
<li class="enens" title="yy_yy"> Sheriff black cat </li>
<li class="odds" title="ss_hu"> It's a strange fate </li>

5) Child element filter selector

annotation : The filtering rules of the child element filter selector are slightly more complex than other selectors , As long as the parent and child elements of the element are clearly distinguished , It's quite easy to use

1)$(":nth-child(idenx/even/odd/equation)") Select... Under each parent element index Child elements or parity elements (idnex from 1 Count up )

:eq(index) Match only one element , and :nth-child The child elements will be matched for each parent element , also :nth-child(index) Of index It's from 1 At the beginning ,

and :eq(index) It's from 0 At the beginning

2)$(":first-child") Select the first child of each parent element ,:first Returns only a single element , and :first-child The selector will match the first... For each parent element

Subelement , for example :$("ul li:first-child"); Select each <ul> One of them <li> Elements

3)$(":last-child") Select the last child of each parent element , Same as above ,:last Return only when an element , and :last-child Selectors will be used for each character

The element matches the last child element , for example :$("ul li:first-child"); Select each <ul> Last of <li> Elements .

4)$(":only-child") If an element is the only child of its parent element , Then it will be matched , If the parent element contains other elements , It won't be matched

$("ul li:only-child") stay <ul> The selection in is the only child element <li> Elements

5):nth-child() Selectors are very common sub element filters , The detailed functions are as follows :

1)$(:nth-child(even)) It can select the elements with even index value under each parent element

2)$(:nth-child(odd)) The index value of each parent element is odd

3)$(:nth-child(2)) The index value under each parent element can be selected to be equal to 2 The elements of

4)$(:nth-child(3n)) The index value that can be selected under each parent element is 3 Elements that are multiples of (n from 1 Start )

5)$(:nth-child(3n+1)) The index value of each parent element can be selected (3n+1) The elements of (n from 1 Start )

6) Form object filter selector : Filter the selected form

1)$(:enabled) Select all available elements ,$("#form :enabled"); selection id by "form" All available elements in the form of

2)$(:disabled) Pick all unavailable elements ,$("#form :enabled"); selection id by "form" All the unavailable elements in the form of

3)$(:checked) Select all selected elements ( Radio buttons , Check box ),$("input:checked") Select all the selected <input> Elements

4)$(:selected) Select all the selected option elements ( The drop-down list ),$("select option:selected") Select all the selected option elements

eg: Light stick effect :

 <script type="text/javascript" src="jq/jQuery1.11.1.js"></script>
<script type="text/javascript">
$(function (){
// Get all li
var lis=document.getElementsByTagName("li"); // To every one. li Registration events
for(var i=0;i<lis.length;i++){
// Change the style"background:pink";
}; lis[i].onmouseout=function(){
// Change the style"background:";
</head> <body>
<li> That's it. Roar, roar </li>
<li> And Party A according to </li>
<li> Fly in another room </li>
<li> And the standard reply is good </li>

(6) Form selector : Convenient access to a form or a certain type of elements

1)$(":input") Pick all <input>,<textarea>,<select>,<button> Elements

2)$(":text") Select all single line text boxes

3)$(":password") Select all password boxes

4)$(":radio") Select all the radio boxes

5)$(":checkbox") Select all the multiple boxes

6)$(":submit") Select all submit buttons

7)$(":image") Select all image buttons

8)$(":reset") Select all Reset buttons

9)$(":button") Select all buttons

10)$(":file") Select all upload fields

11)$(":hidden") Select all invisible elements

eg: Hero alliance :

<script type="text/javascript" src="jq/jQuery1.11.1.js"></script>
<script type="text/javascript"> $(document).ready(function(){
$("#show").css("background-color","pink"); }); }); </script> <style type="text/css">
</head> <body>
<h1 > Hero alliance </h1>
<p class="yx"><< Hero alliance >>, abbreviation LoL.</p> <p>
from <strong>Riot Games</strong> Development , by 3D Arena war games , Its <span class="z"> Main creative team </br> By powerful <strong> World of warcraft </strong> Series of games, multiplayer real-time vs. custom </br> The map development team
</span>..<a href="#"> For more details </a>
</p> <h2> Catalog </h2>
<li id="show"> The development team </li>
<li> Around the game </li>
<li> Introduction to the game </li>
<li> Configuration requirements </li>
<li> Game background </li>

summary :

Pay attention to special symbols and spaces when writing selectors

1) The selector contains ".","、","#","(","]" Equal special character

according to w3c The provisions of the , Attribute cannot contain these special characters , However, in actual projects, we occasionally encounter expressions containing "#","." Equal special character , If we deal with it in a normal way, there may be mistakes , To solve this kind of error is to use escape character to escape

for example :<div id="id#b"> Han Yinglong </div><div id="id[1]"> Han Yinglong </div>, This is the way to do it $("#id\\#b"),$("#id\\[1\\]")

2) Property selector's @ Sign problem

stay Jquery During the upgrade process ,jquery stay 1.3.1 Completely abandoned in the version 1.1.0 A legacy of the version @ Symbol , What you use is 1.3.1 Version above ,

Then you don't need to add @ Symbol , for example :

$("div[@title='test']"), The right way to write it is to remove @ Symbol ,$(div[title='test'])

(2) Notes on spaces in selectors

Spaces in selectors cannot be ignored , One more space or one less space may lead to very different results

Remember what should be remembered , Forget what should be forgotten . Change can change , Accept the unchangeable .

                                                                                                                                                                            Su er an

Use jQuery Fast and efficient production of Web interactive effects more related articles

  1. Use jQuery Fast and efficient production of Web interactive effects ----jQuery Events and animations in

    jQuery In the event and WinForm equally , Interaction in a web page also requires events , for example tab Switching effect , You can do this by clicking on an event . Events play an important role as a bridge between element object and function code . stay JQuery in , event ...

  2. Use jQuery Fast and efficient production of Web interactive effects ---jQuery Selectors

    One . What is? jQuery Selectors Query Selectors inherit CSS And Path Part of the grammar of language , Allow by tag name . Property name or content pair DOM Elements are fast . The right choice , You don't have to worry about browser compatibility , adopt jQuery Selectors are page to page ...

  3. Use jQuery Fast and efficient production of Web interactive effects Chapter 1 JavaScript Basics

    JavaScript One .JavaScript Concept : JavaScript Object oriented event driven scripting language with security , object-oriented JavaScript characteristic : 1. Interpretive language , Explain as you run 2. and HTML Page real ...

  4. Use jQuery Fast and efficient production of Web interactive effects --- Form verification

    Form basic verification technology Why do I need form validation Reduce the pressure on the server Ensure that the input data meets the requirements Common form validation 1. Date format 2. Whether the form element is empty 3. User name and password 4.E-mail Address 5. Id card number Form selector ...

  5. Use jQuery Fast and efficient production of Web interactive effects --- Use jQuery operation DOM

    DOM Operation classification 1.DOM Core: Any kind of support DOM It can be used in any programming language , Such as getElementById() 2:HTML-DOM: Used for processing HTML file , Such as document.forms 3:CS ...

  6. Use jQuery Fast and efficient production of Web interactive effects -- initial jQuery

    One .  jQuery Introduction to basic concepts            1.1 What is? jQuery One javascript library , Write a common method to js In file , Call it directly when you need it jQuery It's just learning some methods     ...

  7. Use jQuery Fast and efficient production of Web interactive effects ---JavaScript Object and initial object orientation

    One .JavaScript Basic data types in number( value type )    string( String type )    boolean( Boolean type )    null( Empty type )    undefined( Undefined type ) ...

  8. Use jQuery Fast and efficient production of Web interactive effects -----JavaScript operation DOM object

    One .DOM Operation classification Use JavaScript operation DOM Time is usually divided into three categories :DOM    Core.HTMl--DOM and CSS-DOM Two . Access to the node Node properties 3、 ... and . Node information Four . Manipulate the properties of the node grammar : ge ...

  9. Use jQuery Fast and efficient production of Web interactive effects --JavaScript operation BOM object

    JavaScript operation BOM One .window object : Two .window Properties and methods of objects Common properties of objects : grammar :window. Property name =" Property value " 2.windo ...

Random recommendation

  1. Small cases of mechanical watch transform Application

    This small case is mainly about transform Application . Of the clock 3 The two hands are 3 individual png picture , adopt setInterval To make the picture rotate . when , branch , The rotation angles of the second are 30,6,6 degree . First , adopt new Date Function to obtain ...

  2. [BZOJ1529][POI2005]ska Piggy banks

    [BZOJ1529][POI2005]ska Piggy banks Test description Byteazar Yes N A piggy bank . Every piggy bank can only be opened or smashed with a key . Byteazar I've put the key to every piggy bank ...

  3. Weblogic Post small questions ——weblogic.descriptor.DescriptorException: VALIDATION PROBLEMS WERE FOUND

    A few days ago, when the app was released, an error message as shown below appeared : weblogic.descriptor.DescriptorException: VALIDATION PROBLEMS WERE FOUND pr ...

  4. POJ 1201 &amp;amp;&amp;amp; HDU 1384 Intervals( Differential braking system )

    Position address :POJ 1201   HDU 1384 According to the meaning of the title . Be able to list inequalities, for example : Sj-Si>=c; Si-S(i-1)>=0; S(i-1)-Si>=-1; Then use the shortest path s ...

  5. MySQL note (Mysql 8.0.16)

    The user login mysql -u user_name -p Change Password ALTER USER 'root'@'localhost' IDENTIFIED BY 'new_password'; Close the service D:\ ...

  6. C Language Check 6_doWhile loop

    Basic grammar do{ Cyclic operation }while( The loop condition ); characteristic : Execute first , To determine Do a loop first eligible , Loop continuation Otherwise, the loop exits Example : #include <stdio.h> #in ...

  7. Windows install zookeeper Stand-alone version

    Installation is required first JdK, from Oracle Of Java Web site to download , Easy to install , Let's not go into details . 1. download zookeeper, ...

  8. Unity And How to delete Unity The useless things in the project ??

    Select what you need to use Scene, Right click to select Select Dependencies, This will select all the files used in this scenario , Export these files as .unitypackage. Use the same method to import all the files of several scenes ...

  9. Codeforces Round #372 (Div. 1) A. Plus and Square Root mathematical problem

    A. Plus and Square Root Topic linking : Description ZS the Coder i ...

  10. miniOrm