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

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().

Related

How to put into querySelector some IDs?

querySelector("#ID1, #ID2, ID#3")
Is there a possibility to put into one querySelector some IDs?
querySelectorAll can be used to target multiple selectors.
document.querySelectorAll("#div1, .div2, h3");
Simple ! Use following code.
document.querySelectorAll('#id1, #id2 , #id3');
This will return nodelist which you can iterate and can perform actions that you want.
The querySelector() method returns the first element that matches a specified CSS selector(s) in the document.
Keep in mind that to return all the matches, use the querySelectorAll() method instead.
example
<div class="bar">.first </div>
<div class="bar">.second</div>
//get the first element with class bar
let firstElement = document.querySelector('.bar');
//log the first match
console.log(firstElement)
//get all elements with class bar
let allElements = document.querySelectorAll('.bar')
//You can use any common looping statement to access the matches
allElements.forEach(function(elements){
console.log(elements);
});
/*
querySelector("#ID1, #ID2, ID#3")
*select element matches #ID1
*select element matches #ID2
*select element matches #ID3
**/
//select elements matches specified selectors #id1 , #id2 , #id3 and use any common looping statement to access them
let allMatchesId = document.querySelectorAll('#id1 , #id2 , #id3');
allMatchesId .forEach(function(elements){
console.log(elements);
});
read the docs here at MDN https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll
const divs = document.querySelectorAll('#id1, #id2');
console.log(divs[0], divs[1]);
<div id="id1"><div id="id2"></div></div>
Source
Just some more explanation:
This will work (if you correct the error ID#3 instead of #ID3), however querySelector only returns the first element in the document that it matches (NOT the first ID in the list).
If you want all of the elements, then use querySelectorAll, but again the order of the elements will NOT be the order of the IDs, but the order of elements in the document. For example, given the following HTML:
<div id="id2"></div>
<div id="id1"></div>
then following JS:
const divs = document.querySelectorAll("#id1, #id2");
alert(divs[0].id); // This will show "id2"!

JQuery: how to remove all div elements except first containing sub-string as 'id' tag?

I have few div elements having id as 'name_a_1', 'name_a_2', 'name_b_3' so on. I want to remove all divs except the first name, which starts from 'name_a_' using JQuery or plain JS?
I successfully tried accessing first and last elements by following JQuery, but how can I access all elements except first?
$('[id^="name_a_"]').first()
$('[id^="name_a_"]').last()
You can use combination :not() and :first selector to target all element except first.
$('[id^="name_a_"]:not(:first)').remove()
or, :gt(index) selector
Select all elements at an index greater than index within the matched set.
$('[id^="name_a_"]:gt(0)').remove()
To check if element have value, .filter() can be used
var hasValue = $('[id^="name_a_"]').filter(function(){
return $(this).val().trim() !== '';
}).length > 0;
Plain JS example using Array.prototype.slice to get all matching elements except for the first.
Array.prototype.slice.call(document.querySelectorAll('[id^="name_a_"]'), 1)
.forEach(elt => elt.parentNode.removeChild(elt))
<ul>
<li id="name_a_1">name_a_1</li>
<li id="name_a_2">name_a_2</li>
<li id="name_a_3">name_a_3</li>
<li id="name_a_4">name_a_4</li>
</ul>
You can also use the .not to exclude the first div:
$('div[id^=name_a]').not(':eq(0)').remove();

jQuery, count n position of element based on matching page/element ID

Ok, so I need to be able to get the n (zero based) position of an element based on a mutual match between the page & element ID...
It's probably easier if I give an example (Assume the current page ID is 488);
<ul id="work-grid">
<li id="item-486" class="work-item"><!--/content--></li>
<li id="item-487" class="work-item"><!--/content--></li>
<li id="item-488" class="work-item"><!--/content--></li>
<li id="item-489" class="work-item"><!--/content--></li>
<li id="item-490" class="work-item"><!--/content--></li>
</ul>
As you can see the list item with the matching numeric ID 488 is the third in the list (So would have an n value of 2).
The problem is, this grid appears on multiple pages (With different ID's) and the list is populated dynamically so I never know the position of the matching element. Is there a way that I can get it using jQuery and add it to the following snippet (Replacing 2 for the correct n position)
$('#work-grid').trigger("colio", ["expand", 2]);
This probably made little to no sense so if anything needs clarification please just let me know.
I think index() is what you want:
var index = $('#item-488').index();
$('#work-grid').trigger("colio", ["expand", index]);
Assuming your element appears once on the page, you can do:
$('#item-488').index();
to find out the index of the element. Read up on index() here: http://api.jquery.com/index/ The bit that applies to this scenario is:
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.
Here's an example: http://jsfiddle.net/bnF6h/
var page = 488;
var a = $( "li[id$='"+ page +"']");
You can use this to dynamically select the item id based on the page id.
Applying it:
var page = 488;
var a = $( "li[id$='"+ page +"']").index();
$('#work-grid').trigger("colio", ["expand", a]);
You mean jQuery's index() method?
http://api.jquery.com/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.

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(...;

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

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/

Categories

Resources