jQuery get index of certain child elements and ignore others - javascript

I'm trying to get the index of a child element ol, but there is also some h2's in there which I don't need and are therefore polluting my results when using the jQuery index() function.
So I need the index of the ol, as if there weren't any h2's at all. So that if you click on the 3rd ol the index will be 2 and not 4.
The HTML looks like this:
<div>
<h2>Title</h2>
<ol><li>Item</li><li>Item</li><li>Item</li></ol>
<h2>Title</h2>
<ol><li>Item</li><li>Item</li><li>Item</li></ol>
<h2>Title</h2>
<ol><li>Item</li><li>Item</li><li>Item</li></ol>
<h2>Title</h2>
<ol><li>Item</li><li>Item</li><li>Item</li></ol>
</div>
And the jQuery:
$('ol li').click(function () {
// get current index position of the ol
var itemIndex = $(this).parent('ol').index();
alert(itemIndex);
});

If I well understood, try this code
var ol = $('ol');
ol.find('li').click(function () {
var parentOl = $(this).parent('ol');
// get current index position of the ol
var itemIndex = ol.index(parentOl);
alert(itemIndex);
});
example jsbin : http://jsbin.com/enugex/1/edit

modify your code on jsfiddle
$('ol li').click(function (item,index) {
// get current index position of the ol
var itemIndex = $(this).parents('div').children('ol').index($(this).parent('ol'));
alert(itemIndex);
});

Try this
$(this).parent('ol').parent().children('ol').indexOf($(this).parent('ol'));

Related

How to find index of li which doesn't have id?

Hi I am creating tabs in JSP using twitter bootstrap.
<ul>
<li id="first">General</li>
<li>Transport</li>
<li>Data Map</li>
<li>Schedule</li>
</ul>
Now I have given id for first LI but dynamically I will be giving id to LI.
How to find the index of LI which does not have id? If the second one has no id, it should find the index of that LI only and should not check for remaining LI How can I get that?
Try with :not .first() and .index():
var idx = $('li:not([id])').first().index();
console.log(idx);
Demo
This will get you the index of first li which doesn't have an id.
You are probably looking for Siblings(). You could also get a reference to the Parent() and go from there.
$('ul li').each(function(index){
$(this).addClass('index-'+index);
});
Example here:
http://jsfiddle.net/superbshivam/HqpSF/
Very quick and dirty approach, but it should get you started on what you need.
var indexWithoutId = -1;
$(document).ready(function() {
findIndexWithoutId();
console.log("without id: " + indexWithoutId);
});
function findIndexWithoutId() {
$("li").each(function() {
var index = $(this).index();
var id = $(this).attr("id");
if (typeof(id) === "undefined") {
indexWithoutId = index;
return false;
}
});
}
Working jsfiddle example
jQuery has a function for this:
$('li').on('click',function(){
alert($(this).index());
});
NB: .index() returns a zero-based index.
Here is a working jsfiddle
To only target li's without an id, make use of the :not() selector and [id] attribute selector:
$('li:not([id])').on('click',function(){
alert($(this).index());
});
Updated jsFiddle
Source(s)
jQuery API - .index()

set array content to title of span tag with JQuery

i have an array like this:
var name = ["cat","shark","tiger","snake"];
i want set array content to <span> title.
HTML CODE:
<ul id="select">
<li class="ui-state-default"><span>CAT</span></li>
<li class="ui-state-default"><span>SHARK</span></li>
<li class="ui-state-default"><span>TIGER</span></li>
<li class="ui-state-default"><span>SNAKE</span></li>
</ul>
jquery code:
for(var i=0; i<=name.length; i++){
$('#select li > span').each(function() {
this.title = name[i];
});
};
but this code don't work.
title of span is be undifined.
If by title you mean the text of the span, I'd suggest:
$('#select li span').text(function(i){
return name[i];
});
JS Fiddle demo.
Or if you're trying to set the title attribute, I'd suggest:
$('#select li span').attr('title',function(i){
return name[i];
});
JS Fiddle demo.
It doesn't make sense to loop over the spans and the array. Also the i <= name.length means that you will always loop past the array (should be <). This means that you were actually setting each span's title to an array element that did not exist.
$('#select li > span').each(function(i) {
$(this).attr('title', name[i]);
});
You may also want to check that name[i] exists.
http://jsfiddle.net/wtbE5/
Try:
$('#select li span').each(function(i){
$(this).html(name[i]);
});
Sample

for loop returning individual letters of one item in array and not each item in the array

I have to arrays that I have made. One grabs some anchor tags and the other a set of ul's. The anchor tags all have a name attribute and the ul's have id's that match the anchor tags name attribute. In addition to this, all the ul's have the class ".students" and ".hidden". (all the .hidden does is set the display:none)
<div>
<ul>
<li><h4><a name="5th-grade">5th Grade</a></h4></li>
<li><h4><a name="6th-grade">6th Grade</a></h4></li>
<li><h4><a name="7th-grade">7th Grade</a></h4></li>
<li><h4><a name="8th-grade">8th Grade</a></h4></li>
</ul>
</div>
<div>
<ul id="5th-grade" class="students hidden ">
<li>Billy Bob</li>
</ul>
<ul id="6th-grade" class="students hidden">
<li>Bob Sackamano</li>
</ul>
<ul id="7th-grade" class="students hidden">
<li>Matt Blunt</li>
</ul>
</div>
What I am trying to do is have it so when I click on one of the anchor tags, it will match it's corresponding name attribute to the ul with the same id, make it appear by removing the ".hidden" class, and then hide any other ul's that do not match by adding the ".hidden" class.
Here is what I have come up with so far using a little jquery and where I stopped:
var aGradelist = $('#grade-list ul li a');
var aStudents = $('.students');
aGradelist.click(function(){
var i = '#' + $(this).attr('name');
$('.students'+i).removeClass('hidden');
for(var j=0;j<aStudents.length;j++)
{
console.log(aStudents.attr('id')[j]);
}
});
It's no problem getting the correct ul's to appear, but I couldn't add the ".hidden" class to the other ul's. I consoled it found that at least one of my problems is in the for loop, I am not going through each ul's in the aStudents array, but through the letters of the id of the first item in the aStudents array.
Am I even approaching this the right way? Have you got some ideas of how to do this?
Provided your html is valid (no duplicated IDs) this should do the trick.
var aGradelist = $('#grade-list ul li a');
var aStudents = $('.students');
aGradelist.click(function() {
aStudents.addClass('hidden');
$('#' + $(this).attr('name')).removeClass('hidden');
});
jQuery iterates over the DOM elements out of the box when you call methods on it.
Also, if you want to know what was wrong with your initial loop, you should use [j] before retrieving the id attribute which is a string. So to retrieve the id property properly:
for(var j=0;j<aStudents.length;j++) {
console.log(aStudents[j].id);
}
$()[j] is a shorthand for $().get(j) (jQuery.fn.get docs).
Try this:
var aGradelist = $('#grade-list ul li a');
var aStudents = $('.students');
aGradelist.click(function(){
var i = '#' + $(this).attr('name');
aStudents.addClass('hidden');
$('ul' + i).removeClass('hidden');
}
What this does is add the hidden class to all the uls and then remove it only from that ul which has the id of the anchor that was clicked

Hide span parent with jQuery if the span contains less than 3 characters

This is driving me nuts... But I surely miss something.
So the HTML looks like:
<ul>
<li><span>Product spec name</span><span>232112412</span></li>
<li><span>Product spec name</span><span>cm</span></li>
<li><span>Product spec name</span><span>80 cm</span></li>
<li><span>Product spec name</span><span>75 cm</span></li>
<li><span>Product spec name</span><span>cm</span></li>
</ul>
So what I want to achieve is to hide those list elements where the second span contains less than or equal to 2 characters.
I thought about putting them into a variable, loop through them, and if the length of the current item is less than or equal to 2 then jQuery should hide its parent.
Heres the code I wrote:
$(document).ready(function () {
var pspec = $('ul li span:nth-child(2)');
for(i=0;i<pspec.length;i++) {
if($(pspec[i]).text().length <= 2) {
$(this).parent().hide();
}
}
});
But this code won't do the trick... I still consider myself a jQuery beginner so please would You be so kind to help me out on this one?
Thanks in advance!
Best Wishes,
Matt
Demo: http://jsfiddle.net/PFaav/
$(document).ready(function () {
$('ul li').filter(function () {
return $(this).find('span').eq(1).text().length <= 2;
}).hide();
});
Your code will work if you replace
$(this).parent().hide();
by this
$(pspec[i]).parent().hide();
Try below,
$(document).ready(function(){
$.each ($('ul li'), function (idx, el) {
var $span = $(this).find('span').eq(1); //2nd span
if ($span.text().length <= 2) {
$span.parent().hide();
}
});
});
use the filter function
$('ul li span:nth-child(2)').filter(function() {
return $(this).text().length < 3; // <-- get 2nd span elements whose text length < 3
}).parent().hide();​ // <-- hide parent elements of the returned elements
http://jsfiddle.net/y9dSU/
You could use jQuery each instead of using for and mixing jquery and javascript,
$(document).ready(function(){
var pspec = $('ul li span:nth-child(2)').each(function(){
if($(this).text().length <= 2) {
$(this).parent().hide();
}
});
});

loop through list with sublists javascript

ul
li1
li2
ul3
li3.1
li3.2
ul3.3
ul3.3.1
ul3.3.2
li4
li5
and I must check all items in ul3 I can't be sure if there is only two or three or more lists
Well, I don't know what you mean by "check", but you can have a function be called for each <li> like this:
$('li').each(function() {
// whatever "check" means
});
With just plain Javascript:
var nodes = document.getElementsByTagName('li');
for (var i = 0; i < nodes.length; ++i) {
var li = nodes[i];
// check ...
}
edit — well it's not clear what exactly you need, but if you just need to inspect <li> elements in lists that are themselves in <li> elements, then you'd just code that into the jQuery selector:
$('ul ul li').each(function() { ... });
Use the each() like this:
$('ul li').each(function(){
// your code.....
});
This will loop through the ul children at any nested level.
Update:
and I must check all items in ul3 I
can't be sure if there is only two or
three or more lists
Try this in that case:
$('ul:eq(2) li').each(function(){
// your code.....
});
This will start from third ul and find its children at any nested level.

Categories