earachefl
earachefl

Reputation: 1890

jQuery closest() question

To all: sorry if I've not understood the protocol here at StackOverflow. I will immediately endeavor to correct my standing within the community. Having said that:

I'm trying to change the context of a jQuery function depending upon what calls it. In the following code, when the page first loads, we see that the limitDates() function is called with HTMLElementDiv as the current context. When we call it by typing in the input field, we see that it's not a div, but trying to get the parent div using $(this).closest('div') returns an HTMLElementInput, not the div. Any thoughts?

update: have created a fiddle: http://jsfiddle.net/earachefl/XBFNQ/8/

<script type="text/javascript" src="common/js/jquery-1.5.2.min.js"></script>
<script type="text/javascript" src="common/js/jquery-ui-1.8.12.custom.min.js" ></script>

<div class="datemodule">
    <input class="date_from" type="text" id="date_from_#name#" name="date_from" value=#start#>
</div>

<script>
    $(document).ready(function(){
        $('div.datemodule').limitDates();
        $('.date_from').keydown(function(){
            $(this).limitDates();
        });
    });

    (function($){
        $.fn.limitDates = function(){                   
            return this.each(function(){
                context = $(this).context;
                //alert(context);
                alert(context.nodeName);
                if (context.nodeName != 'DIV'){
                    alert('not a div');
                    newContext = $(this).closest('div').context;
                    alert(newContext.nodeName);
                }
            });
        };
    })(jQuery);
</script>

Upvotes: 2

Views: 613

Answers (2)

James Montagne
James Montagne

Reputation: 78640

The description of context is :

The DOM node context originally passed to jQuery();

So even after calling closest the context is still the original input passed to jQuery.

If you want to get the div, why not just get it?

newContext = $(this).closest('div')[0];

Upvotes: 1

Yiğit Yener
Yiğit Yener

Reputation: 5986

Context is the DOM element that is passed to JQuery(). So your selectors in the first place have both the context as document.

$('div.datemodule').limitDates(); // context is the document
$('.date_from').keydown(...   // context is the document

When it comes to a callback, if you use $(this) context is the element that triggers the event.

$('.date_from').keydown(function(){
    $(this).limitDates();         // context is the element which has class .date_form and triggered that event
}); 

And when it comes to your function where you use this.each the context is set to each element in each iteration.

return this.each(function(){
    $(this).context; // context is the element of iteration
}

As i said context is what is passed to JQuery and probably it is readonly.

Upvotes: 2

Related Questions