DG3
DG3

Reputation: 5298

jquery select specific child

What is wrong with the below code. I am trying to loop over children of a specific id, and assigning a css class only to specific children.

var firstRC = $("#id_1").children();
    for(j=0;j<firstRC.length;j++) {
       if(j>5) {
        $("#id_1:eq(j)").addClass("cssClass");
       }

    }

Upvotes: 1

Views: 3119

Answers (3)

RoToRa
RoToRa

Reputation: 38400

Because the j in the jQuery selector is just a part of the string and not a variable. You'll need to create the selector string by concatenation:

var firstRC = $("#id_1").children();
  for(j=0;j<firstRC.length;j++) {
    if(j>5) {
      $("#id_1 :eq(" + j + ")").addClass("cssClass");
    }
  }

Also you need a space before :eq, or you'll select the j-th element with the id id_1 and not the j-th child inside an element with id_1.

However you are doing it far to complicated. jQuery has a gt selector allowing you to select all elements *g*reater *t*han a specific index:

$("#id_1 :gt(5)").addClass("cssClass");

If you do need to loop over several elements you should ccheck out jQuery's each method, that is much better easier to use than a for loop. Inside the each loop, this refers to the current element.

Example:

$("#id_1").children().each(function(index) {
   if (index > 5)
      $(this).addClass("cssClass");
});

Upvotes: 1

jAndy
jAndy

Reputation: 236022

Use a :gt selector or .slice() method to get the nodes you need.

$("#id_1").children().slice(5).addClass("cssClass");

ref.: .slice()
example: http://www.jsfiddle.net/xDN9D/

Upvotes: 1

Jonathon Bolster
Jonathon Bolster

Reputation: 15961

Your problem is that the j variable is as a string. You need to bring it back into the JavaScript code.

var firstRC = $("#id_1").children();
for(j=0;j<firstRC.length;j++) {
   if(j>5) {
    $("#id_1:eq(" + j + ")").addClass("cssClass");
   }
}

Of course, if you're trying to set the class for everything greater than 5 you could do this:

$("#id_1 :gt(5)").addClass("cssClass");

Example: http://jsfiddle.net/jonathon/8sydw/1/

Upvotes: 1

Related Questions