user3265085
user3265085

Reputation: 25

Create own JQuery Plugin

I want to create a very simple Jquery Plugin. What it does is return the parent of the element. I searched and tried many different methods, still can't get it to run.

(function($){
$.fn.extend({
    getParent:function(){

        return this.each(function(){$(this).parent()}); 

    }


    });
})(JQuery);

in html

<script type="text/javascript">
    $(document).ready(function(e) {
alert($("#demos").getParent());
    });
</script>

it should alert the parent of the $("#demos")

Upvotes: -1

Views: 104

Answers (3)

ced-b
ced-b

Reputation: 4065

JQuery this.each() returns just the items in this. So you will not get the parents by doing an each but only the selected item again.

If you would do just...

 return $(this).parent();

...you would get what you want.

Upvotes: 0

Kiran
Kiran

Reputation: 20313

You have typo here:

Replace JQuery with jQuery.

(function($){
$.fn.extend({
    getParent:function(){
        return this.each(function(){$(this).parent()}); 
    }
    });
})(jQuery);

$(document).ready(function() {
console.log($("#demos").getParent());
});

<div id="parent">
    <div id="demos"></div>
</div>

DEMO

Upvotes: 2

Saravana
Saravana

Reputation: 40554

You have a typo in your plugin. It's jQuery, not JQuery.

(function($){
$.fn.extend({
    getParent:function(){

        return this.each(function(){$(this).parent()}); 

    }


    });
})(jQuery);

Upvotes: 1

Related Questions