Sunday, November 26, 2017

Part 3 - What are jQuery Selectors? | ID and class selectors




What are selectors in jQuery? 

A jQuery selectors selects or finds a DOM element in an HTML document. It is used to select HTML elements based on id, name, types, attributes, class etc. 
popular selectors
  1. Id selectors
  2. Class selectors
  3. Element selectors
  4. Attribute selectors
For selecting input elements like Select, TextArea, Button, Image, Radio etc. we can use $(“:input”) selector. It will return a collection of input elements.
 Example: $(":input[type='button']") , $(":input[type='radio']")

ID and Class selectors
In this tutorial only ID and class selectors are explained. If we select element by its id the we need to use $('#element_id') and if we access element by class name then we need to  use $('.ClassName')

# Example
Replace your html code with below code and try to show alert on button click in Jquery

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script src="jquery-3.2.1.min.js"></script>

    <script>

        $(document).ready(function () {

           //Class selector example
            $(".div1,.div2").css({ "border": "2px solid red", "padding": "10px" });

            //Id selector example
            // $("#myDiv").css({ "border": "2px solid blue", "padding": "10px" });

        })

    </script>

</head>
<body>

    <div id="myDiv" class="div1" style="margin-bottom:50px;padding:10px">
        <button>click</button>
        <span>child1  </span>
    </div>

    <div class="div2" style="padding:10px">
        <button>click</button>
        <span>child2  </span>
    </div>

</body>
</html>


No comments: