Here is my HTML and when tag was click I want to know that what is its <li> siblings number was. Please Advice me please.
<div id="tabs">
<ul>
<li class="select" >Hotel</li>
<li >Airfare</li>
<li >Package</li>
</ul>
</div>
and here is my javascript.
// I don't want to input 1 in the function tabSelector
// I want to get parent's sibling value automatic and
// change somthing in li class.
$('#tabHotel').click(function(){
tabSelector(1);
});
you could use index().
$("#tabs").on("click", "li", function(){
alert($(this).index());
});
in your case:
tabSelector($(this).index() + 1 );
Demo:
http://jsfiddle.net/P3KjZ/1/
You can use jQuery's index() method to achieve this I believe.
index() - If no argument is passed to the .index() method, the return value is
an integer indicating the position of the first element within the
jQuery object relative to its sibling elements.
If .index() is called on a collection of elements and a DOM element or
jQuery object is passed in, .index() returns an integer indicating the
position of the passed element relative to the original collection
Here's a jsFiddle example.
For the technical number (first is equal to 0) you'd use:
$('li').on('click', function(){
console.log($(this).index());
});
For the literal number (first element is equal to one) you'd just add one to the index instead:
$('li').on('click', function(){
console.log($(this).index()+1);
});
to get exact number you will be required to add 1 to the index. please try below one
$("#tabs").on("click", "li", function(){
alert($(this).index()+1)
})
Related
jQuery newbie here.
If I have this html:
<ul id="floor-selector">
<li id="floor-1">Ground Floor</li>
<li id="floor-2">Second Floor</li>
<li id="floor-3">Third Floor</li>
<li id="floor-4">Premier Floor (Premier Floor)</li>
</ul>
I want to add a click event to each li item, such that I can get the id of the element I am on. Right now I just have an alert with the index I'm on (and it's not working either), but I really want the ID of the item I'm on, not the index of the array returned by my selector.
Here's what I tried, but it doesn't seem to work, I think I might have the wrong understanding of each() or click().
$('#floor-selector li').each( function(index, node) {
node.click( function(){ alert('I am on the '+index+'th element'); } );
// but I really want to get the ID of this element
});
This should work:
$('#floor-selector li').on('click', function() {
alert('I am the '+$(this).attr('id')+' element');
});
Behind the scenes jQuery does a bunch of magic and essentially binds the function you pass to the element. this therefore references the element that you are clicking and passing it to jQuery functio: $(this) gives you back that element wrapped in a jQuery object. Of course you could simply access the id on this directly.
I'm by no means a jQuery (or JavaScript) expert so forgive me if I'm misunderstanding or overlooking something. I have the following HTML:
<html>
<body>
<div class="ted">Ted</div>
<div class="ted">Ted</div>
<div class="tim">Tim</div>
<div class="ted">Ted</div>
<div class="tim">Tim</div>
</body>
</html>
And the following JS:
$('.ted').click(function() {
alert($(this).index());
});
When I click a div with the class '.ted' the alert should show the index of that div.
Clicking the first div alerts '0' (expected), the second div alerts '1' (expected). However, clicking the last '.ted' div (the fourth in the list) alerts '3' - why is this not giving an index of 2? (as JS arrays are 0 based) and this is the third '.ted' div?
It's as if $('.ted') is actually bringing back all the divs in the list?
Example here: http://jsfiddle.net/nha2f/6/
The .index() method docs make this behaviour clear. Here's the relevant part (emphasis added):
If no argument is passed to the .index() method, the return value is an integer indicating the position of the first element within the jQuery object relative to its sibling elements.
Since the third element that matches your selector is actually the fourth child of its parent, it has an index of 3.
Continue reading through the documentation to find the solution to your problem:
If a selector string is passed as an argument, .index() returns an integer indicating the position of the original element relative to the elements matched by the selector.
So, you can pass the same selector to .index() and it will return the index of the element relative to the matched set:
alert($(this).index(".ted"));
.index() returns the index of the clicked element in it's parent, relative to it's siblings. Not compared to other divs with the same event listeners / class / id. Your third '.ted' div is the fourth child of your body.
To get the behavior you want, add a selector to your index call: Fiddle
$('.ted').click(function() {
alert($(this).index(".ted"));
});
When you pass a selector into index, it tells jQuery to look for the element in that set. If you don't, it looks to see where it is relative to all of its sibling elements.
Or alternately, remember the list of ted elements and then invert things: Fiddle
var teds = $(".ted");
teds.click(function() {
alert(teds.index(this));
});
When you pass an element into index, that tells jQuery to look for that element in the set.
the index is the child within the parent. If you want to enumerate the .ted elements try this:
$('.ted').each( function( i, a ){
$(a).click( function(){
alert( i ); // <- should be 0, 1 or 2.
} );
} );
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')
I have the following HTML:
<ul actualpage=0>
<li/>
<li/>
....
</ul>
<ul actualpage=0>
<li/>
<li/>
....
</ul>
Im trying to get the value of actualpage of each ul and create a new attribute. Its easy but not in one jquery sentence... Its possible? Until now i have the following line (between ## simbols the missing part that i need.
/*
select all uls with attribute actualpage and create a new attribute on each with the current actualpage value
*/
$('ul[actualpage]').attr('newactualpage',##Current value of actualpage attr of UL##);
Well maybe this isn't as nice as you'd like, but
$('ul[actualpage]').each(function(_, ul) { $(ul).attr('newactualpage', $(ul).attr('actualpage')); });
One might think that
$('ul[actualpage]').attr('newactualpage',$(this).attr('actualpage'))
is the answer.
However, this is evaluated before the call to attr, so it's going to equal whatever this equals in the calling context.
You could use:
$('ul[actualpage]').attr('newactualpage',function(){
return $(this).attr('actualpage');
});
or this:
$('ul[actualpage]').each(function()
{
$(this).attr('newactualpage',$(this).attr('actualpage'));
};
In both, this refers to the element that your selector matched.
You can use function as second argument for .attr(), eliminating the need of .each():
$('ul[actualpage]').attr('newactualpage', function() { return $(this).attr('actualpage') });
The JQuery "has" method effectively selects all elements where they have particular descendants.
I want to select elements based on the fact they have particular ancestors. I know about parent([selector]) and parents([selector]) but these select the parents and not the children with the parents.
So is there an ancestor equivalent of "has"?
Note: I already have the context of an element further down the hierarchy and I will be selecting based on this so I can't do a "top down" query.
Update
I've obviously explained myself really badly here, so I'll try and clarify:
<ul class="x">
<li>1</li>
<li>2</li>
<li>3</li>
</ul>
<ul class="y">
<li>4</li>
<li>5</li>
<li>6</li>
</ul>
I have a jQuery object that already consists of elements 2,3,4 and 5. I want to select those elements who have a parent with the class = x.
Hope that makes more sense.
For a clean re-usable solution, consider extending the jQuery.fn object with a custom method used for determining the presence of a particular ancestor for any given element:
// Extend jQuery.fn with our new method
jQuery.extend( jQuery.fn, {
// Name of our method & one argument (the parent selector)
within: function( pSelector ) {
// Returns a subset of items using jQuery.filter
return this.filter(function(){
// Return truthy/falsey based on presence in parent
return $(this).closest( pSelector ).length;
});
}
});
This results in a new method, $.fn.within, that we can use to filter our results:
$("li").within(".x").css("background", "red");
This selects all list items on the document, and then filters to only those that have .x as an ancestor. Because this uses jQuery internally, you could pass in a more complicated selector:
$("li").within(".x, .y").css("background", "red");
This will filter the collection to items that descend from either .x or .y, or both.
Fiddle: http://jsfiddle.net/jonathansampson/6GMN5/
if ( $('.foo').parents('.parentSelector').length ) { // has parent }
If I understand your question correctly, this would do:
$.fn.hasAncestor = function(a) {
return this.filter(function() {
return !!$(this).closest(a).length;
});
};
$('.element').hasAncestor('.container').myAction();
<div class="container">
<span>
<strong class="element">strong</strong>
</span>
</div>
$('body').hasParent('html') //true
$('div#myDiv').hasParent($('body')) //true
#API:
// check if current element has parent element 'e'
$.fn.hasParent = function (e) {
return !!$(this).parents(e).length
}
You can actually use filter directly (without a function calling closest) and it will have better performance. Simply use a selector that matches elements contained within .x:
$("li").filter(".x *")
this also differs slightly from the closest solutions suggested by others in that it will not match if the element itself has the given class but only if it is within an element with that class.
If matching an element with the class is desired as well, this could be modified slightly:
$("li").filter(".x, .x *")
$("li").filter(".x *").css("background", "red");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="x"><li>1</li><li>2</li><li>3</li></ul>
<ul class="y"><li>4</li><li>5</li><li>6</li></ul>
Try this
ul.myList > li > a
This selector selects only links that are direct children of list elements, which are
in turn direct children of elements that have the class myList.
object.each(function(){
element = $(this);
if(element.parent().hasClass("x")){
//do stuff
}
});
this will affect every item in your object that has parent .x
The easy way is this:
// all children of a specific parent match
$('parentSelector').children();
// All children matching a specific pattern, one level deep
$('parentSelector > childSelector');
// or
// $('parentSelector').children('childSelector');
// All children matching a specific pattern, multiple levels deep
$('parentSelector childSelector');
// or
// $('parentSelector').find('childSelector');
or did you really need something more complicated than that?
Edit: If you already have an element, you can combine this with the parent() command, like so:
myElement.parents('parentSelector').find('childSelector'); // Will include self
I realize this is an old question, but I'm leaving this here for future visitors looking for something similar;
There is a $.contains(container, contained) method which returns a boolean.
https://api.jquery.com/jQuery.contains/
Very simple way to do it
$('.x').find('li')