Home » JQuery

Selectors in JQuery

JQuery Selectors: In this tutorial, we are going to learn about the selectors in JQuery.
Submitted by Siddhant Verma, on November 16, 2019

It's time to write some JQuery now. Do check out the introductory article on JQuery first in case you haven't. Before we move to Selectors in JQuery, let's talk a bit about the general syntax first.

Statements

Almost everything in JQuery is a statement. This may not be the first time you're hearing this because most programming languages conceive every distinguishable line of code as a statement. In JQuery, all statements are preceded with a $ (dollar sign). This is also known as the JQuery keyword. For instance,

    document.getElementById("#sub-text");
    $("#sub-text");

We have used a CSS selector above using JQuery. You can see how easy it is to select an element using a CSS selector in JQuery. You just write the JQuery keyword ($ sign) followed by a pair of parentheses ( () ) and put the CSS selector inside those parentheses.

The above two statements, the former in Vanilla JS and the later in JQuery essentially do the same thing however there is a small, subtle yet important difference to note. Before we understand that and start coding some JQuery let's create a simple HTML page that we can play around with. I'm taking this boilerplate from the introductory article. All I have done till now is added materialize CDN for writing cool styles quickly and link to our local stylesheet,

Index.html

<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <!-- Compiled and minified CSS -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">

    <!-- Compiled and minified JavaScript -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>
    <link rel="stylesheet" href="styles.css">
</head>

<body>

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    <script src="index.js"></script>
</body>

</html>

Let's add some content quickly so we can start using JQuery

<div class="container">
    <h1 class="title">Explaining JQuery to Spongebob</h1>
    <p id="intro-text">Can I say one word or two about Spongebob first?</p>
    <div class="row">
    </div>
    <div class="card">
        <div class="card-content">
            <h5 class="sub-title">List of names of spongebob's buddies are</h5>
            <ul class="center collection" id="list">
                <li>Mr Krabs</li>
                <li>Garry</li>
                <li>Squidward Tentacles</li>
                <li>Mrs Puff</li>
            </ul>
        </div>
    </div>
</div>

Output

selectors in JQuery | Example 1

Now that we have the template setup, let's first see that subtle difference we spoke about,

    console.log(document.querySelector('.title'));
    console.log($('.title'));

The above two statements should essentially do the same thing, and they actually do. They both get us a reference to the HTML element with a class name of the title. However,

Output

    <h1 class="title">Explaining JQuery to Spongebob >/h1>
    k.fn.init [h1.title, prevObject: k.fn.init(1)]

The second statement returns us somewhat an array wrapped around the element. It looks a lot like an array however, to be accurate it's a JQuery Object. No matter what you reference to, a JQuery statement always returns a JQuery Object. You can also verify this,

    typeof(title);

Output

    "Object"

Why JQuery wraps elements in a JQuery object wrapper is simply because we have loads of different properties and methods available to us then? This becomes very useful when we're animating elements using JQuery.

    title.animate;

Output

    ƒ (t,e,n,r){var i=k.isEmptyObject(t),o=k.speed(e,n,r),a=function(){var e=dt(this,k.extend({},t),o);(i||Q.get(this,"finish"))&&e.stop(!0)};return a.finish=a,i||!1===o.queue?this.each(a):this.queue(o.que...

However, we also have the freedom to unwrap our element and return a regular Vanilla JS object and use the common Vanilla JS methods available on it.

    title[0];

Output

    <h1 class="title">Explaining JQuery to Spongebob</h1>

Notice how the 0th element inside the JQuery object is actually that HTML element so we can simply obtain it using the indexing method. However, now we don't have access to the animation methods,

    title[0].animate;

Output

    ƒ animate() { [native code] }

Selectors are used to grab content from the web page. We can use simple CSS selectors to grab elements from the DOM using JQuery.

    const title=$('.container h1');
    console.log(title);

Output

    k.fn.init [h1.title, prevObject: k.fn.init(1)]

We can also target ids.

    const list=$('#list');
    console.log(list);

Output

	k.fn.init [ul#list.center.collection]
	0: ul#list.center.collection
	length: 1
	__proto__: Object(0)

If you know CSS, using JQuery selectors will come super easy to you.

    list[0];

Output

    <ul class="center collection" id="list">...</ul>

We can also get the first <li> using,

    const firstFriend=$('ul li:first')[0];
    console.log(firstFriend);

Output

    <li>Mr. Krabs</li>

The *is the universal selectors and grabs the whole HTML of the page.

    const everything=$('*')[0];
    console.log(everything);

Output

    <html lang="en"><head>…</head><body cz-shortcut-listen="true">...</body></html>






Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.