Thursday, 15 December 2011

jQuery Selectors

jQuery selectors allow you to select and manipulate HTML elements as a group or as a single element.

jQuery Element Selectors

jQuery uses CSS selectors to select HTML elements.
  • $("p") selects all <p> elements.
  • $("p.intro") selects all <p> elements with class="intro".
  • $("p#demo") selects all <p> elements with id="demo".

jQuery Attribute Selectors

jQuery uses XPath expressions to select elements with given attributes.
  • $("[href]") select all elements with an href attribute.
  • $("[href='#']") select all elements with an href value equal to "#".
  • $("[href!='#']") select all elements with an href attribute NOT equal to "#".
  • $("[href$='.jpg']") select all elements with an href attribute that ends with ".jpg".

    jQuery CSS Selectors

    jQuery CSS selectors can be used to change CSS properties for HTML elements.
    The following example changes the background-color of all p elements to red :

    syntax:
    <html>
    <head>
    <script type="text/javascript" src="jquery.js"></script>
    <script type="text/javascript">
    $(document).ready(function(){
      $("button").click(function(){
        $("p").css("background-color","red");
      });
    });
    </script>
    </head>

    <body>
    <h2>This is a heading</h2>
    <p>This is a paragraph.</p>
    <p>This is another paragraph.</p>
    <button>Click me</button>
    </body>
    </html>

    Example with syntax:

    $(this) Current HTML element
    $("p") All <p> elements
    $("p.intro") All <p> elements with class="intro"
    $("p#intro") All <p> elements with id="intro"
    $("p#intro:first") The first <p> element with id="intro"
    $(".intro") All elements with class="intro"
    $("#intro") The first element with id="intro"
    $("ul li:first") The first <li> element of each <ul>
    $("[href$='.jpg']") All elements with an href attribute that ends with ".jpg"
    $("div#intro .head") All elements with class="head" inside a <div> element with id="intro"

     

No comments:

Post a Comment