Solved

Check Position in a jQuery Selector Array

Posted on 2011-09-07
11
325 Views
Last Modified: 2012-06-21
Let's say I have this in my HTML:

<div id="myList">
	<ul>
	  <li>foo</li>
 	  <li>bar</li>
 	  <li>baz</li>
	</ul>
</div>

Open in new window



In my javascript/jquery, I start off my setting a variable that I'll increment.

var j = 0;

Open in new window


Then, using jquery, I want to select all the list (<li>) items, and do something to each of them. I can set up this shell:

$('#myList ul li').each(function() {
	//do something here
	})

Open in new window





My understanding is that the $('#myList ul li') returns an array, but it's not a DOM array. Rather it's an array of those DOM elements wrapped in jQuery so that I can perform more stuff on them. Is that right?

At any rate, I'm failing to see how I can check to see if the $(this) for "each" one matches a certain position in the array.

In other words, in plain English, I want something like this:


function myFunction() {

	$('#myList ul li').each(function() {

		if ("this" is the one in the j position) { //do something to it }

		else { //do something else to the other "etches" that don't match the j position }	


	})


}

Open in new window


Then, later on in the script, I increment j, so that the next time I run myFunction, it does the "something" to the next item, and the "something else" the others.


I've looked into .index(), .inArray(), and traditional myArray[j] types of things… but I'm a lightweight in javascript and know even less in jQeury, so I am getting confused.

Can anyone help me check that index number in my function above?


0
Comment
Question by:caf210
  • 5
  • 4
  • 2
11 Comments
 
LVL 51

Expert Comment

by:HainKurt
ID: 36498291
use this

$('#myList ul li').each(function(index) {
      //do something here
      alert(index);
      })
0
 
LVL 51

Expert Comment

by:HainKurt
ID: 36498300
or something like this

$('#myList ul li').each(function(index) {
  //do something here
  alert(index + " : " + $(this).html());
})
0
 

Author Comment

by:caf210
ID: 36498377
Thanks, HainKurt. But I'm not having any luck with that solution.
0
 
LVL 51

Expert Comment

by:HainKurt
ID: 36498424
i dont see why? above function gives you index & html of li elements...

what part is not working? here is the full sample
<html>
<head>
			<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript" ></script>
<script>
$(document).ready(function() {
//add functions here
$('#myList ul li').each(function(index) {
	//do something here
	alert(index + " : " + $(this).html());
	})
});
</script>
</head>

<body>

<div id="myList">
	<ul>
	  <li>foo</li>
 	  <li>bar</li>
 	  <li>baz</li>
	</ul>
</div>

</body>
</html>

Open in new window

0
 
LVL 51

Accepted Solution

by:
HainKurt earned 250 total points
ID: 36498466
here is another sample, check this sample how I use js variable and index together
<html>
<head>
			<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript" ></script>
<script>
var i=0;
function checkItems(){
  $('#myList ul li').each(function(index) {
	//do something here
	if (index==i) alert(index + " : " + $(this).html());
	});
	i++; if (i==3) i=0;
};
</script>
</head>

<body>

<div id="myList">
	<ul>
	  <li>foo</li>
 	  <li>bar</li>
 	  <li>baz</li>
	</ul>
</div>
<button onClick="checkItems()">test</button>
</body>
</html>

Open in new window

0
How to improve team productivity

Quip adds documents, spreadsheets, and tasklists to your Slack experience
- Elevate ideas to Quip docs
- Share Quip docs in Slack
- Get notified of changes to your docs
- Available on iOS/Android/Desktop/Web
- Online/Offline

 

Author Comment

by:caf210
ID: 36498498
Thanks, HainKurt.

Let me go through these carefully and then I'll get back to you.
0
 
LVL 19

Assisted Solution

by:Albert Van Halen
Albert Van Halen earned 250 total points
ID: 36498531
Looping the jquery object with 'each' sets the context (this) to each of the DOM elements within the array.
In order to wrap the DOM element into a jquery object $ is used : $(this).

Like HainKurt says; an argument in the each function (i.e. index) is the position of the element in the array; hence a loop-counter.
So you can match the 'j' variable to the 'index' variable used in the each method.

Another option is to use the eq method of the jquery object. See http://api.jquery.com/eq/
eq will return a jquery object having the n-th element of the selector.

$("#mylist ul li").eq(j)
0
 

Author Comment

by:caf210
ID: 36498732
Thanks guys.

HainKurt: This did work for me after all. Maybe something else with my script was crashing it earlier. My apologies for jumping the gun.

Albert: Thanks for the explanation and the eq method, too. One thing that is throwing me a bit is the use of the "index" argument. Most of my experience is with ActionScript, and in that, which is similar, I think when you put an argument in your function, like this...

function myFunction (myArg) {
//function
}

...you have to specify something when calling it, like this:

myFunction("passThisIn");

Otherwise, this...

myFunction();

...would throw an error for differences on "expected arguments."

Does index, as a word in the language, automatically get recognized without a definition in this example?


--

What I'm going to do is up the points from 250 to 500, and then split them between the two of you. Thanks for your help!
0
 

Author Closing Comment

by:caf210
ID: 36498743
I was helped here by two very knowledgeable folks. This solved my problem by showing me how to reference the index.
0
 
LVL 19

Expert Comment

by:Albert Van Halen
ID: 36501424
caf210, you don't have to specify anything when calling the method in javascript.
myFunction() or myFunction(param) will execute the same function : myFunction.
You won't get any exceptions.

However if the definition of your method is like function myFunction(param) {} you may check if the argument param is set or not.

The index provided in your anonymous function within the jQuery each method is provided through jQuery.
jQuery is looping through the array and executes the method providing the loopcounter as an argument.
In your method you can call it whatever you like. In this example the word index is used.
0
 

Author Comment

by:caf210
ID: 36502569
Thanks, Albert. That's very interesting. I appreciate your sharing your knowledge with me.
0

Featured Post

6 Surprising Benefits of Threat Intelligence

All sorts of threat intelligence is available on the web. Intelligence you can learn from, and use to anticipate and prepare for future attacks.

Join & Write a Comment

Nothing in an HTTP request can be trusted, including HTTP headers and form data.  A form token is a tool that can be used to guard against request forgeries (CSRF).  This article shows an improved approach to form tokens, making it more difficult to…
This article discusses how to create an extensible mechanism for linked drop downs.
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
In this fourth video of the Xpdf series, we discuss and demonstrate the PDFinfo utility, which retrieves the contents of a PDF's Info Dictionary, as well as some other information, including the page count. We show how to isolate the page count in a…

705 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

18 Experts available now in Live!

Get 1:1 Help Now