tags:

views:

29

answers:

4

Have a tough one here!

I'm creating a blogger template, and the client wants varying colours applied to headings in the right column of the template.

The problem is, I have little control over the html generated as it is controlled by the blogger engine.

What I want to be able to do, is:

Select Nth instance of an h2 element with a class of 'title', and apply a css style using Jquery.

A limiting factor is that it seems Jquery wants you to tell it what the parent element is so it can count elements. In this design however, the element could appear any where, and it is the instance count for the entire page I am interested in. Correct me if I'm wrong here.

I have tried the following code without success - an attempt to use the indirect decendance CSS selector:

$(document).ready(function () {

            alert('test');

            $("#RightColContent S+ h2.title:nth-child(2)").css('background-color', 'green');
            $("#RightColContent S+ h2.title:nth-child(3)").css('background-color', 'red');
        });

This code applied the style, but to all elements, presumably because I have not supplied a parent element:

$("h2.title:nth-child(1)").css('background-color', 'green');

Please see the firebog html inspection image to see the html flow.

alt text

Kudos to anyone who can help me with this.

A: 

This should work:

$("h2.title:eq(n)")

It selects all h2's having the class title, and then returns the nth item from that list. Remember that eq is 0 indexed, so you would actually put n-1 to get the nth element above.

See a simple example.

Anurag
Would appreciate if the downvoter mentions reasoning.
Anurag
A: 

What I want to be able to do, is:

Select Nth instance of an h2 element with a class of 'title', and apply a css style using Jquery.

$('h2.title:eq(N-1)').css('property', 'value');

http://api.jquery.com/eq-selector/

or

$('h2.title').eq(N-1).css('property', 'value');

http://api.jquery.com/eq/

just somebody
+1  A: 

use the eq selector like so

$('h2.title:eq(4)')    //selects the 5th element in the selection
wowo_999
It should be eq(3) to get the 4th element since they are 0 indexed.
Anurag
Kudos, and to every one else who chipped in. Thanks very much
BombDefused
A: 

You could also load each h2, then apply the colors using jquery.each:

$('#RightColContent h2.title').each(function(index) {
    //apply your different css classes to each item
    $(this).addclass('title' + index);
  });

In your css, you would create a rule for each index class:

.title1 { color: red;}
.title2 { color: blue;}
.title3 { color: green;}
Chris Fletcher