How to select descendants of this in jQuery? - javascript

CODE:
$(this).html("<table><tr><td></td><td></td><td></td></tr><tr><td></td><td></td><td></td></tr><tr><td></td><td></td><td></td></tr></table>");
$(this "td").each(function(index){ //i want a selector somewhat like this (to select td descendants if this)
//mycode
});
Please suggest a syntactically correct selector

Pass this as second parameter to set the context
$("td",this).each(function(index){ //i want a selector somewhat like this (to select td descendants if this)
//mycode
});
Or use $(this).find('td') method, this case yo can get reference back to $(this) using end() method.
$(this).find("td").each(function(index){ //i want a selector somewhat like this (to select td descendants if this)
//mycode
});

jQuery has quite a few ways to target all of the child elements that appear beneath beneath a specific element via the find() function or by simply using the context parameter of a normal selector :
// This will use the find() function to find all <td> elements under this element
$(this).find('td').each(function(index){ ... });
// This will do the same thing (selecting all <td> elements with this as the context)
$('td',this).each(function(index){ ... });

Related

How do I use the child element of 'this' as a selector in jQuery?

I have a function that calls when the user mouseover a certain div. The function shows a different div, but the issue is that it shows all of the divs with that class.
Here's the JS:
$('.edit-image').mouseover(
function(e){
$('.edit-image-link').show();
});
What I want it to do is only show the .edit-image-link div if it's a child of the element that the user has their mouse over.
You can use .find() to fetch only the descendant elements of an element based on a selector.
$('.edit-image').mouseover(function (e) {
$(this).find('.edit-image-link').show();
});
or you can pass a context to jQuery for searching a selector
$('.edit-image').mouseover(function (e) {
$('.edit-image-link', this).show();
});
Note: Inside a jQuery callback method like event handlers, this will refer the to current dom element
I personally prefer the first method
Use
$('.edit-image').mouseover(function () {
$(this).find('.edit-image-link').show();
});
References
this keyword
.find()
Get the descendants of each element in the current set of matched
elements, filtered by a selector, jQuery object, or element.

Jquery toggle just the p tags under the div clicked

Quick, simple question.
I have this function working at the moment ;
$("#menuopties").click(function(){
$("p").toggle();
});
However this toggles every p tag.
I just want to toggle the p tags which are under the div #menuopties (which has been clicked)
Thanks.
Your current selector "p" will get all the elements of type p instead of getting the p within the current object. Use find() to get the descendant of current element. you will get the source of event object using $(this)
$("#menuopties").click(function(){
$(this).find("p").toggle();
});
You can use pass current object in context of the selector using jQuery( selector [, context ] )
$("#menuopties").click(function(){
$("p", this).toggle();
});
Try like this
$("#menuopties").click(function(){
$(this).find("p").toggle();
});
How about:
$("p", this).toggle();
try:
$("#menuopties").click(function(){
$(this).find("p").toggle();
});
hope that helped.
Change $('p').toggle(); to $(this).children('p').toggle();
$(this) refers to the current jQuery object (in this case wrapping the #menuopties DOM element), so running .children() allows you to filter its descendant elements by whatever selector you want (in this case p).
edit: as buzzsawddog pointed out, it's important to note .children() only returns the child elements a single level below in the DOM, so if your p tags are not immediate children of #menuopties you should use .find() instead.

How to get the container id in javascript or in jquery

I have some HTML blocks look like
<li id="item261">
<div class="itemdesc">
<a class="icon-hide">Hide</a>
</div>
</li>
And i have a jquery like
$(document).ready(function()
{
$('.icon-hide').click(function(){
var elemId = $(this).parent().attr("id");
});
});
I need the ID of the "li" tag on click of ".icon-hide". how can i achive this? any help..
I'd suggest:
$('.icon-hide').click(function(){
var elemId = $(this).closest('li').attr('id');
});
This is because parent() as implied in the name of the method looks at the parent of the element returned by the selector (the parent is the div); whereas closest() continues up the ancestor tree to match the first selector passed to the method.
You could, instead, use parents(), however the important difference between closest() and parents() is that closest() returns zero or one match, whereas parents() will continue all the way to the root element and return every match it finds, so it can return zero, one or many matches.
Another difference is that parents() starts searching from the current element's parent, whereas closest() starts with the current element itself, so it's quite easily possible, using closest() for the method to return the current/$(this) element itself.
References:
closest().
parent().
parents().
$(this).closest('li[id]').attr('id')

How to get a Selector using this

I have a Selector in a Selector. I want the inner Selector to select only those elements, that are also selected by the outer Selector.
This is what my naiveté came up with:
$('.some-class').hover(function() {
$( this + '.another-class');
})
Put differently, I want the elements with with another-class AND which are children of the element that is hovering. How do I do that?
Use the children() method.
$('.some-class').hover(function() {
$(this).children('.another-class');
});
This method falls under the traversal category, which allows you to select ancestors, descendants, siblings etc all from the current element.
$('.some-class').hover(function() {
$(this).find('.another-class');
})
This Keyword represent Object
You need to try this
jQuery(".another-class", this);
More detail

Selecting only one element in the jQuery collection

How do I limit an event to a single element in a jQuery collection?
In the case below, I've tried using .one() to limit the behaviour (inserting the <li class='close'>Close</li> line of HTML) to a single instance. The behaviour does indeed happen only once, but on EVERY matched element of $( "ul>li>a" ). How do I make it happen only once, to only ONE of the matched elements in the collection?
Any ideas?
$( "ul>li>a" ).one(
"click",
function(){
$( "ul ul")
.prepend("<li class='close'>Close</li>")
}
);
Thanks in advance.
-AS
A jQuery selection returns an array. Therefore $("selection")[0] can work. However there are better abstracted methods for this, like .get(0) or .first() (in case you're looking for the first element of the selection/array).
$("selection").get(index) returns the pure DOM element (at that specific index) of the selection, and is not wrapped in the jQuery object.
$("selection").first() returns the first element of the selection, and wraps it in a jQuery object.
So if you don't necessarely want to return the first element, but still want jQuery functionality, you can do $($("selection").get(index)).
Given your situation, this should work fine:
// bind the 'onclick' event only on the first element of the selection
$( "ul>li>a" ).first().click(function() {
$( "ul ul").prepend("<li class='close'>Close</li>");
});
Which is equivalent to this:
$($( "ul>li>a" ).get(0)).click(function() {
$( "ul ul").prepend("<li class='close'>Close</li>");
});
And this:
$($( "ul>li>a" )[0]).click(function() {
$( "ul ul").prepend("<li class='close'>Close</li>");
});
I must disagree with Ryan, working on the CSS selection string to filter the result is rather expensive compared to the native JavaScript array functionality.
Try first(), it selects the first element:
$( "ul>li>a" ).first().one('click',
function(){
$( "ul ul").prepend("<li class='close'>Close</li>")
}
);
one() is used, as you already noticed, to handle an event only once.
You have to specify the index of the element you want to work with.
If your selector returns more than one element you can do one of a couple things...
You can isolate your elements by giving them a class or id attribute in your html and alter the selector to select only the class/id of the element/s you wish to select or you can specify the index of the element you're trying to work with. The later method is a bit sloppy but works as long as your page structure doesn't ever change.
So for the first method I spoke of you'd change your selector to this after applying a class/id to your elements:
$("ul>li>a.class")
or
$("ul>li>a#id")
For the second method I mentioned you'd change your selector to this:
$("ul>li>a:eq(index)")
Where index is the zero based index of the element you're trying to select.
You can call the first method, which will return a new jQuery object containing only the first element in the original one.
However, in your case, you might as well use the (equivalent) :first selector, like this:
$("ul > li > a:first").click(function() { ... });
If you only want to handle the first click event and ignore any subsequent clicks, you'll need to use .one(), like you already are.
You need to combine first() with one():
$( "ul>li>a" ).first().one('click', function () {});
More general:
$( "ul>li>a:eq(n)" ).one('click', function () {});

Categories