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?
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.
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.
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.
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.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With