JQuery Interview Questions Part -1

1)What is the use of Delegate() Method in jQuery?
Ans)
The delegate() method can be used in two ways.
1) If you have a parent element, and you want to attach an event to each one of its child elements, this delegate() method is used.
Ex:Un-ordered List
Instead of attaching an event to each
  • element, you can attach a single event to element.
    Example:
    $("ul").delegate("li", "click", function(){
    $(this).hide();
    });
    2) When an element is not available on the current page, this method is used.
    .live() method is also used for the same purpose but, delegate() method is a bit faster.
    Example:
    $("ul").live("li", "click", function(){
    $(this).hide();
    });
    This will hide any list items that are not currently available on the page. They may be loaded via an Ajax request and then append to it.
    Using .bind() or .click() methods, you would have to manually attach events to these new list items once they are added.
    ---------------------------------------------------------------
    2)Can we select a element having a specific class in jQuery ?
    Ans)
    Yes, we can select an element with a specific class, we use the class selector.The class name must contain the prefix as "." (dot).


    <script language="javascript" type="text/javascript">
    $(".class1").css("border", "2px solid red");
    </script>

    Above code will select all the elements of the webpage containing the class as "class1" and apply the css style border width as 2 Pixel, style as solid and color as red.