How to apply style to the nth instance of a class and find it by indirect inheritance - CSS JQuery

Take the tough here!

I am creating a blogger template and the client wants different colors to be applied to the headings in the right column of the template.

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

I want to be able to:

Select the nth instance of the h2 element with the "title" class and apply the CSS style using jQuery.

The limiting factor is that it seems that Jquery wants you to tell it what the parent element is, so that it can count the elements. However, in this design, an element can appear anywhere, and this is the number of instances for the entire page that interests me. Correct me if I am wrong here.

I tried the following code without success - trying to use the indirect CSS decryption 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, apparently because I did not provide a parent element:

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

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

alt text http://bombdefused.com/firebug.png

Kudos to anyone who can help me.

+3
source share
5 answers

use the eq selector this way

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

This should work:

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

It selects all h2 having the class name, and then returns the nth element from this list. Remember that eq is indexed to 0, so you really would put in n-1to get the nth element above.

. .

0

:

N- h2 "title" css, JQuery.

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

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

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

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

0
source

You can also load every h2 and then apply 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 will create a rule for each index class:

.title1 { color: red;}
.title2 { color: blue;}
.title3 { color: green;}
0
source

use : eq
$('h2.title:eq('+i+')');
or : nth-of-type
$('h2.title:nth-of-type('+i+1+')');
or even something as simple as:
$($('h2.title')[i]); where $('h2.title')[i]is a JavaScript element and $($('h2.title')[i])a jQuery element .

0
source

Source: https://habr.com/ru/post/1752510/


All Articles