Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Possible to target element by nth-child "globally"?

Suppose I have a hierararchy like:

ul
    li
    li

ul 
    li
    li      <----- 
    li              

Can I target the marked li by li:nth-child(4) or something similar?

like image 384
Jiew Meng Avatar asked Jun 11 '13 09:06

Jiew Meng


People also ask

What is the use of nth child in HTML?

Definition and Usage. The :nth-child ( n) selector matches every element that is the n th child, regardless of type, of its parent. Tip: Look at the :nth-of-type () selector to select the element that is the n th child, of a particular type, of its parent.

How do I get the nth child of an element?

Use the querySelector () method to get the nth child of an element, e.g. document.querySelector ('#parent :nth-child (3)'). The :nth-child pseudo class returns the element that matches the provided position.

Can you add a filter to the “nth child”?

Luckily, you don’t always have to do the math yourself—there are several :nth-child testers and generators out there: There is a little-known filter that can be added to :nth-child according to the CSS Selectors specification: The ability to select the :nth-child of a subset of elements, using the of format.

What is the nth child of a selector?

The :nth-child(n) selector matches every element that is the nth child, regardless of type, of its parent. n can be a number, a keyword, or a formula.


1 Answers

You can do this using jQuery.

User jQuery.eq();

Try this simple Example (jsFiddle).

<!DOCTYPE html>
    <html>
    <head>
        <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
        <script type="text/javascript">
            $(function(){
                $("li:eq(6)").css("color", "red");
            });
        </script>
    </head>
    <body>
        <ul>
            <li>1</li>
            <li>2</li>
            <li>3</li>
            <li>4</li>
        </ul>

        <ul>
            <li>5</li>
            <li>6</li>
            <li>7</li>
            <li>8</li>
        </ul>   
    </body>
</html>
like image 70
Dipesh Parmar Avatar answered Sep 23 '22 02:09

Dipesh Parmar