jQuery Selectors

What is jQuery Selectors?

jQuery is a open source library written JavaScript code. The purpose of jQuery is to make it much easier to use JavaScript on your website.

jQuery selectors are used to find or select HTML elements based on their name, id, classes, types, attributes, values of attributes and much more. It's based on the existing CSS Selectors, and in addition, it has some own custom selectors.
The following table shows the basic illustration of CSS and jQuery Selectors
Element CSS Selector jQuery Selector Description
HTML element p $('p') Select all p element
ID #myId $('#myId') Select the element with id="myId"
Class .myClass $('.myClass') Select all elements with class="myClass"
* * $('*') Select all elements

1. $("#myId")
The jQuery #myId selector uses the id attribute of an HTML tag to find the specific element.
$(document).ready(function(){
    $("button").click(function(){
        $("#myId").toggle();
    });
});
Demo: https://jsfiddle.net/quanghoan/zz6q797a/

2. $("#myClass")
The jQuery class selector finds elements with a specific class.
Demo: https://jsfiddle.net/quanghoan/zz6q797a/1/

3. $(this)
Select current element: https://jsfiddle.net/quanghoan/zz6q797a/2/
$(document).ready(function(){
    $("button").click(function(){
        $(this).hide();
    });
});

4. $("p.myClass")
 Selects all <p> elements with class="myClass".
$(document).ready(function(){
    $("button").click(function(){
        $("p.myClass").toggle();
    });
});
Demo: https://jsfiddle.net/quanghoan/zz6q797a/3/

5. $(".myClass,#myId")
All elements with the class "myClass" or with the id "myId"
$(document).ready(function(){
    $("button").click(function(){
        $(".myClass,#myId").css("background-color","red");
    });
});
Demo: https://jsfiddle.net/quanghoan/zz6q797a/4/

6. $("div")
$(document).ready(function(){
    $("button").click(function(){
        $("div").animate({
            left: '250px',
            opacity: '0.5',
            height: '150px',
            width: '150px'
    });
});
Demo: https://jsfiddle.net/quanghoan/zz6q797a/5/

If you liked this article

Let's subscribe the updates of Scuti!
Share on Google Plus

About Quang Hoan

This is a short description in the author block about the author. You edit it by entering text in the "Biographical Info" field in the user admin panel.
    Blogger Comment
    Facebook Comment

0 Comments:

Post a Comment