gb2d gb2d - 6 months ago 16
CSS Question

How to apply style to Nth instance of class, and find by indirect inheritance - CSS Jquery

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.

Answer

use the eq selector like so

$('h2.title:eq(4)')    //selects the 5th element in the selection