Reputation: 4094
The original problem I face is like this:
$('#setting-box > div').change(function(){
// Would like to select current div's span child and do something
}
I have done some research and found this post: How to get the children of the $(this) selector?
The two parameters way actually works for me
$('span', this).html($('input', this).val());
And now my question is, is there any method to select this span element,
using single parameter in the $()? (and not using method like find(), child(), etc)
Like, is there any thing / way to do $(this > childElement)
?
Thanks for any help
Upvotes: 1
Views: 83
Reputation: 388436
the exact replacement is
$(this).children('span').html($('input', this).val());
or try (not tested)
$('> span', this).html($('input', this).val());
Upvotes: 1
Reputation: 708056
To answer your question directly, there is no single argument way to just search children of the this
element in jQuery. That's because the default context for jQuery is the entire document so to change that, you HAVE to use some additional code besides just the selector.
Further, a DOM element itself (in the this
variable in your example) can't go into a selector because the selector is a string and a DOM element doesn't have any way to express it in a selector string. So, you have to use an extra argument to qualify what scope is searched for the selector to something smaller than just the document.
So, to restrict the scope of the selector search, that leaves you with the options that it sounds like you may already know about:
$(this).find(selector) // any descendant
$(selector, this) // any descendant
$(this).children(selector) // only look at direct children
If I want any descendant, I myself prefer to use .find()
because I think the code is more directly readable. So, for your particular need, I'd use this:
var self = $(this);
self.find("span").html(self.find("input").val());
Or, if only direct children:
var self = $(this);
self.children("span").html(self.children("input").val());
In addition, your .change()
code should be bound to an element that actually supports that event which would be something like a <select>
or <input>
, not a regular <div>
.
Upvotes: 3