0
<!doctype html>
<html>
    <head>
        <meta charset="utf-8" />
        <title>Demo</title>
        <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
        <script>
            var headings = $('h3');
            var paras = $('p');
            paras.hide().eq(0).show();
            headings.click(function() {
                var cur = $(this); //save the element that has been clicked for easy referal
                cur.siblings('p').hide(); //hide all the paragraphs
                cur.next('p').show(); //get the next paragraph after the clicked header and show it
            });
        </script>
        <style type="text/css">
            p,h3 {margin: 0; padding: 0;}
            p {height: 150px; width: 200px; border: 1px solid black;}
            h3 {height: 50px; width: 200px; background-color: blue; color: white; border: 1px solid black;}
        </style>
    </head>
    <body>
        <h3>Item 1 </h3>
        <p>Item 1 content</p>
        <h3>Item 2 </h3>
        <p>Item 2 content</p>
        <h3>Item 3 </h3>
        <p>Item 3 content</p>
        <h3>Item 4</h3>
        <p>Item 4 content</p>
    </body>    
</html>

Above code is taken from here: http://www.1stwebdesigner.com/tutorials/jquery-for-complete-beginners-part-3/

Question:

for this line: var cur = $(this); I know this means the h3 that has been clicked, but why we can not write this way: var cur = this; what is the difference between this and $(this) here?

Thirumalai murugan
  • 5,698
  • 8
  • 32
  • 54
user2294256
  • 1,029
  • 1
  • 13
  • 22

4 Answers4

5
$(this)

converts the DOM element returned by this to a jQuery object, from which, you can continue using jQuery on.

ddavison
  • 28,221
  • 15
  • 85
  • 110
2

this is a reference to the member that invokes the current function

For example

$(document).ready(function(){
    $("#test").click(function(){

var jQuerizedElement = $( this ); // instead of calling it by its selector you can use this
  });
});

Now you can do more stuff with it.

Panama Jack
  • 24,158
  • 10
  • 63
  • 95
2

this returns the DOM element, whereas $(this) returns the jQuery object.

this

is equivalent to

$(this).get()
vijrox
  • 1,063
  • 1
  • 13
  • 33
0

$ is the shorthand for the jQuery function. You could also write:

var cur = jQuery(this);

jQuery "wraps" around DOM elements and other objects in order to give them more functionality. Just like you pass a selector string into the jQuery constructor, you can pass a native DOM element (which this is) and it'll become a jQuery object.

Blender
  • 289,723
  • 53
  • 439
  • 496