jQuery Selector

jQuery Selector

In this tutorial, we will tall about the selector which is the most important parts in the jQuery library.What we do most in jQuery is selecting the DOM elements and manipulate them.


There are many ways to search and control HTML elements:
There are 3 most frequently used methods:

1.jQuery selector by ID


Syntax: $("#id")

We use it instead of document.getDocumentById method.
It will search the element with this id from the DOM.
Example:

<div id="another"><p>id="another"</p></div>
<div id="foo">id="foo"</div>
$("#foo");
//will get
//<div id="foo">id="foo"</div>

2. jQuery selector by class


Syntax: $(".class") // begin with period(full point)

It will select all elements with the given class.For example:
Find out all elements with the class "myClass".

<div class="notMe">div class="notMe"</div>
<div class="myClass">div class="myClass"</div>
<span class="myClass">span class="myClass"</span>
$(".myClass");

It will match these elements,no matter what html tag is:

<div class="myClass">div class="myClass"</div>
<span class="myClass">span class="myClass"</span>

3. jQuery selector by element(HTML tag name)


Syntax: $("element")

It will search all elements with the given tag name.
We use it instead of document.getElementsByTagName method.

<div>DIV1</div>
<div>DIV2</div>
<span>SPAN</span>

find the div elements:

$("div");

Result:

<div>DIV1</div>
<div>DIV2</div>

Combination selector


We can combine the selectors to make a new one.
For example:

<div class="myClass">DIV1</div>
<div class="notMe">DIV2</div>
<span class="myClass">SPAN1</span>
<span class="notMe">SPAN2</span>
<p class="myClass">P</p>

Finds SPAN element with myClass class:

$("SPAN.myClass"); // not myClassSPAN,it would be confused with class selector

Result:

<span class="myClass">SPAN1</span>
$("p.myClass,SPAN.myClass"); //get the combined results of p and span with myClass

Result:

<span class="myClass">SPAN1</span>
<p class="myClass">P</p>

Other jQuery selector


$("*") select all dom elements

<div class="hightlight">DIV1</div>
<div class="foo">DIV2</div>
<span id="bar">SPAN1</span>
<span>SPAN2</span>
<p class="foo">p</p>
var selector = $("*");
var elementCount = selector.length; // get the number of all matched elements.

$( "parent > child" )

How to select the element under special element.
The child combinator (E > F) selects only first-level descendants.
Example:

<ul class="topnav">
  <li class="myClass">Item 1</li>
  <li>Item 2
    <ul class="nav">
    <li class="nav-item">Nested item 1</li>
    <li class="nav-item">Nested item 2</li>
    <li class="nav-item myClass">Nested item 3</li>
    </ul>
  </li>
  <li>Item 3</li>
</ul>

Selector:

$(".topnav > .myClass")
  1. get elements with class myClass
    <li class="myClass">Item 1</li>
    <li class="nav-item myClass">Nested item 3</li>

  2. filter out the element which's parent has the class topnav
    <li class="myClass">Item 1</li> matched.

So $(".topnav > .myClass") will only select first-level descendants under topnav div
Result:

<ul class="topnav">
  <li class="myClass">Item 1</li> <-- this one

$("ancestor descendant")

This selector will select all the elements under a given ancestor.Usually used with filter or iteration just like .find() ,.each() methods.

Difference between $( "select1 > select2" ) and $( "select1 select2" ): The > means only direct children of the element select1.
Example:

<ul class="topnav">
  <li class="myClass">Item 1</li>
  <li>Item 2
    <ul class="nav">
    <li class="nav-item">Nested item 1</li>
    <li class="nav-item">Nested item 2</li>
    <li class="nav-item myClass">Nested item 3</li>
    </ul>
  </li>
  <li>Item 3</li>
</ul>

How to get all child li item of a ul element?

the selector $("ul.topnav li") will select all elements that are descendants of ul.topnav element. There are 6 matches.

<li class="myClass">Item 1</li> // first element matched
<li>Item 2                     // second element matched
  <ul class="nav">
  <li class="nav-item">Nested item 1</li>
  <li class="nav-item">Nested item 2</li>
  <li class="nav-item myClass">Nested item 3</li>
  </ul>
</li>
<li>Item 3</li> // third element matched

<li class="nav-item">Nested item 1</li> // fourth element matched
<li class="nav-item">Nested item 2</li> // fifth element matched
<li class="nav-item myClass">Nested item 3</li> // sixth element matched

$( "prev + next" )

select all nextelements which next to prev.

<label class="username" for="name">Name:</label>
  <input name="name" id="name">
  <fieldset>
    <label for="newsletter">Newsletter:</label>
    <input name="newsletter" id="newsletter">
  </fieldset>

the selector $("label.username + input") will only match the input element with id name. Because newsletter is not the sibling of username Label.


$( "prev ~ next" )

Select all sibling elements after the "prev" element, which match the filter "siblings" selector.
For example:

<form>
  <label>Name:</label>
  <input name="name" />
  <fieldset>
      <label>Newsletter:</label>
      <input name="newsletter" />
 </fieldset>
</form>
<input name="none" />

select all sibling element after "form" and they should match the input selector filter:
$("form ~ input")
the result is:
[ <input name="none" /> ]

Filters


We have learn the basic selectors. When search elements ,we put the conditions in the $(). If we want more detailed results, we can add more conditions or use the Filters.


Basic Filters Selectors

There are 13 basic filters.

FilterDescription
:animatedselect all elements executing animation effects
:eq(n)Select the element at index n within the matched set.
:evenSelects even elements, zero-indexed
:firstSelects the first matched DOM element.
:gt()Select all elements at an index greater than index within the matched set.
:headerSelects all elements that are headers, like h1, h2, h3 and so on.
:lang()Selects all elements of the specified language.
:lastSelects the last matched element.
:lt()Select all elements at an index less than index within the matched set.
:not()Selects all elements that do not match the given selector.
:oddSelects odd elements, zero-indexed
:rootSelects the element that is the root of the document.
:targetSelects the target element indicated by the fragment identifier of the document's URI.


Examples


  1. how to find first visible input?
    $('form').find('*').filter(':input');


  1. How to set option selected in a select element with jQuery?

<select id="select1">
  <option value="1">blabla</option>
  <option value="2">blabla</option>
  <option value="3">blabla</option>
</select>

Solution:

$("#select1 option:first").attr('selected','selected');
$("#select1 option:eq(2)").attr('selected','selected'); // set second option is selected
$("#select1 option:selected").prop("selected", false); // use prop instead of attr

  1. how to select div elements according to their language?

<h3>USA</h3>
<div lang="en-us">red
  <div>white
    <div>and blue</div>
  </div>
</div>
<h3>España</h3>
<div lang="es-es">rojo
  <div>amarillo
    <div>y rojo</div>
  </div>
</div>

the selector $("div:lang(en)")will match <div lang="en"> and <div lang="en-us">, but not <div lang="es-es">.


Content Filters Selectors

There are 4 content filters which use their content as part of a condition.

FilterDescription
:contains('text')match all elements that contain text.
:emptymatch all elements that have no children (including text nodes)
:has(selector)match elements which contain at least one element that matches selector.
:parentmatch all elements that have at least one child node (either an element or text).

Attribute Selectors

There are 9 selectors based on attributes.
the [] selector syntax allows you to check against any of the elements attributes.

Attribute SelectorDescription
[name|="value"]Select all elements which has name attribute with a value either equal to value or starting with value followed by a hyphen (-).
[name*="value"]Selects elements that have name attribute with a value containing value.
[name~="value"]Selects elements that have the specified attributename with a value containing a given word value, delimited by spaces.
[name$="value"]Selects elements that have the specified attribute with a value ending exactly with a given string. The comparison is case sensitive.
[name="value"]Selects elements that have the specified attribute with a value exactly equal to a certain value.
[name!="value"]Select elements that either don't have the specified attribute, or do have the specified attribute but not with a certain value.
[name^="value"]Selects elements that have the specified attribute with a value beginning exactly with a given string.
[name]Selects elements that have the specified attribute, with any value.
[name="value"][name2="value2"]Matches elements that match all of the specified attribute filters.

Child Filters

Child FiltersDescription
:first-childSelects all elements that are the first child of their parent.
:first-of-typeSelects all elements that are the first among siblings of the same element name.
:last-childSelects all elements that are the last child of their parent.
:last-of-typeSelects all elements that are the last among siblings of the same element name.
:nth-child()Selects all elements that are the nth-child of their parent.
:nth-last-child()Selects all elements that are the nth-child of their parent, counting from the last element to the first.
:nth-last-of-type()Selects all the elements that are the nth-child of their parent in relation to siblings with the same element name, counting from the last element to the first.
:nth-of-type()Selects all elements that are the nth child of their parent in relation to siblings with the same element name.
:only-childSelects all elements that are the only child of their parent.
:only-of-type()Selects all elements that have no siblings with the same element name.


 <ul>
    <li>Glen</li>
    <li>Tane</li> <-- $( "ul li:nth-child(2)" )
    <li>Ralph</li><-- $( "ul li:nth-last-child(2)" ) ,counting from the last to first
    <li>David</li>
  </ul>

Visibility Filters

Visibility FiltersDescription
:hiddenMatches all elements that are hidden.
:visibleMatches all elements that are visible.

Forms Selectors

Forms SelectorDescription
:buttonSelects all button elements and elements of type button.
:checkboxSelects all elements of type checkbox.
:checkedMatches all elements that are checked or selected.
:disabledSelects all elements that are disabled.
:enabledSelects all elements that are enabled.
:focusSelects element if it is currently focused.
:fileSelects all elements of type file.
:imageSelects all elements of type image.
:inputSelects all input, textarea, select and button elements.
:passwordSelects all elements of type password.
:radioSelects all elements of type radio.
:resetSelects all elements of type reset.
:selectedSelects all elements that are selected.
:submitSelects all elements of type submit.
:texSelects all input elements of type text.
date2019-04-02 17:58:00 From:www.jquerypluginhub.com Author:JPH
Related Tags:
Comments

Leave a Reply

Your email address will not be published. Required fields are marked *