Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

Check Position in a jQuery Selector Array

Posted on 2011-09-07
11
Medium Priority
?
340 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 5
  • 4
  • 2
11 Comments
 
LVL 59

Expert Comment

by:HainKurt
ID: 36498291
use this

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

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
Give Your Engineering Team a Productivity Boost

Learn why container technology is so powerful and how it can provide your team with productivity gains and other benefits.

 
LVL 59

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 59

Accepted Solution

by:
HainKurt earned 1000 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
 

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 1000 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

Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

SASS allows you to treat your CSS code in a more OOP way. Let's have a look on how you can structure your code in order for it to be easily maintained and reused.
Without even knowing it, most of us are using web applications on a daily basis.  In fact, Gmail and Yahoo email, Twitter, Facebook, and eBay are used by most of us daily—and they are web applications. We generally confuse these web applications to…
The viewer will learn how to create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …
Learn how to create flexible layouts using relative units in CSS.  New relative units added in CSS3 include vw(viewports width), vh(viewports height), vmin(minimum of viewports height and width), and vmax (maximum of viewports height and width).

722 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