jQuery best practice for $($(".elem")[0])? - javascript

Is there a way to only use ONE dollar sign instead of doing this?
$($(".elem")[0]).hide()
I could use :first, but what about if I wanted the third or so:
$($(".elem")[2]).hide()

Use .eq() function
$(".elem").eq(3).hide()
Description: Reduce the set of matched elements to the one at the specified index.
.eq( index )
indexAn integer indicating the 0-based position of the element.
And
.eq( -index )
-indexAn integer indicating the position of the element, counting backwards from the last element in the set.
And it is 0 index based, so third would be .eq(2)

You can use, :eq
$('.test:eq(2)').hide(); //hides the third encounter of an element with class .test
There is also :nth-child( x ) but it grabs a child element.
Read more,
http://api.jquery.com/eq-selector/
http://api.jquery.com/nth-child-selector/

Related

Select second to last element

i need to select the value of second to last input selectable element:
<tr><td><select class="x">...</select></td></tr>
<tr><td><select class="x">...</select></td></tr>
<tr><td><select class="x">...</select></td></tr>
The select input tag are inside tr tags.
If I use $("select.x").last(), jQuery select the last element. I need to select second to last.
You can use .eq() with negative indexes:
$("select.x").eq(-2);
These negative indexes are "1-indexed": -1 gives the last element, -2 the penultimate, and so on.
You can use .prev()
$("select.x").last().prev();
All of the below will do the trick (select the second last element):
$("select.x").eq(select.length - 1)
$("select.x:nth-last-of-type(2)")
$("select.x:nth-last-child(2)")
$("select.x").last().prev()
You can use :last selector and move to the preceding element using prev:
$("select.x:last").prev();
Ref:
Get the immediately preceding sibling of each element in the set of
matched elements, optionally filtered by a selector.
Sample demo: http://jsfiddle.net/IrvinDominin/ck8XP/
You need to use "nth-last-child(2)" of jquery, this selects the second last element.
You can check this here:
https://api.jquery.com/nth-last-child-selector/
The solutions with .prev() or nth-last-child() don't works.
<tr><td><a>...</a><select class="x"></select><a>...</a><td><tr>
<tr><td><a>...</a><select class="x"></select><a>...</a><td><tr>
<tr><td><a>...</a><select class="x"></select><a>...</a><td><tr>
<tr><td><a>...</a><select class="x"></select><a>...</a><td><tr>
The problem is the last().prev() functions return the the object <a> which i suppouse come first the select one.
The nth-last-of-type(2) selector instead return an empty object.

How can I use jQuery to match nth-child or last if nth not found?

I need to be able to insert some markup into a document after() the second P element in a container. If there is only one element then I need to insert after() that one. nth-child simply does not make a match if there is only one element. How can I do this?
Thanks!
Select them both, and grab the first match.
$("#foo > p:nth-child(2), #foo > p:lastChild").eq(0).append(...;
Because the results are returned in document order, you can use the 0 index to get the nth-child or if it wasn't there, it'll get the last child.
If there are other element types, and you only care about the p elements, then use nth-of-type instead.
$("#foo > p:nth-of-type(2), #foo > p:lastChild").eq(0).append(...;

Targeting CSS on div range

I have an element I populate with $.ajax now I want to fade all the custom loaded elements, the element is already pre-populated with 20 elements when the page loads, I don't want to target those 20. Essentially, how can I target the latter 17 divs assuming I have 37 divs total? Currently I use:
while ($(".info #future>center>div").length>20) {
$(".info #future>center>div:last-child").remove();
}
to remove them, but now I also want a fading effect to be applied prior, assigning anything to their class is not an option since that property is already taken.
you can use `slice() Slice() method of jquery. Given a jQuery object that represents a set of DOM elements, the .slice() method constructs a new jQuery object containing a subset of the elements specified by the start and, optionally, end argument. The supplied start index identifies the position of one of the elements in the set; if end is omitted, all elements after this one will be included in the result.
$('.info #future>center>div').slice(20).remove(); //Where start and end your index to filter. I omitted end parameter. if you want you can put it. .slice(20,37)
if you want fading effect
$('.info #future>center>div').slice(20).fadeOut(300, function() { $(this).remove(); });
take look on jQuery :gt() Selector.
it used to select all elements at an index greater than index provided to it so you can call it with index = 20
$(".info #future>center>div:gt(20)").remove();

How to find index of list item (ul-li)?

I have a jQuery object that is an HTML li element. How do I find what is the index of it in the context of its parent ul?
So if I have this:
<ul>
<li>abc</li>
<li id="test">def</li>
<li>hij</li>
</ul>
And this object:
$("test")
Is there a way to get the index number of this element. In this case it would be 1 (if you count 0 being the first index). Is there something I can do with $("test").parent()?
You can simply use $("#test").index(). Note the use of the id selector #.
When .index() is called without any parameters,
the return value is an integer indicating the position of the first
element within the jQuery object relative to its sibling elements.
In this case this would be 1 -- see it in action.
.index() is what you're looking for. Evaluates against its siblings, see the jQuery documentation.
You can use index():
var index = $('#test').index();
Or, you can supply a selector, to get the index from a different set of matched elements:
var index = $('#test').index('li.className');
Which will get the index point for the #test element from among those elements with the .className (assuming that #test also had this class).
References:
index().

Why is the following jQuery selector not returning both elements?

I've run into a situation where I am creating a jQuery object from an html string and need to select all elements within it with a particular class.
What I'm finding odd is that its returning one or the other, depending on which type of selecting mechanism I'm using. A test case is shown here:
var tmpl = '<ul><li class="foo">TEST</li></ul><div class="foo">BAR</div>';
console.log( $('.foo', tmpl) ); //[<li class="foo">TEST</li>]
console.log( $(tmpl).find('.foo') ); //[<li class="foo">TEST</li>]
console.log( $(tmpl).filter('.foo') ); //[<div class="foo">BAR</div>]
http://jsfiddle.net/Rfq9F/
In this example, both an li element in a ul and a non-descendant div have the class "foo". In the example, I use the .foo selector and set context to the template string. Second, I use .find() on the string. Finally, I use .filter() on the string.
Can someone explain why the selector mechanisms are acting as they do, and also how to achieve the goal I mentioned in the beginning?
It's because it's not a single root node, but two (ul and div).
Wrap everything in a <div> and it will work:
http://jsfiddle.net/Rfq9F/3/
Calling $(tmpl) creates a set with two elements - the <ul> element and the <div class="foo"> element. .find() looks for elements that are descendents of any of the elements in the set that match the selector. .filter() returns any elements in the set that match the selector.
The first two lines:
console.log( $('.foo', tmpl) );
console.log( $(tmpl).find('.foo') );
are equivalent, they're just two different ways to write the same thing.

Categories

Resources