Reputation: 168249
Is there a way to select a DOM's only_child
, n-th-child
, etc? I know that there are selectors like some_tag:only-child
, .some_class:only-child
, #some_id:only-child
, but that selects based on the tag or attributes (class, id, etc.) of itself. What I want is to do selection based on the tag or attribute of the parent.
For example, I might want to select the only-child
of .some_class
, which is the div with id B
below, not the only-child
that is .some_class
, which is A
.
<div>
<div class="some_class" id="A">
<div id="B">
</div>
</div>
</div>
Upvotes: 1
Views: 771
Reputation: 724452
If you're looking for the only child of .some_class
, you need to separate the class selector and the pseudo-class with a combinator. Parent-child and ancestor-descendant relationships between two different sets of selectors are always indicated with a combinator (the child combinator and descendant combinator respectively).
Given your HTML, you'll want to use the child combinator >
to limit it to the only element that's directly nested within .some_class
:
.some_class > :only-child
Upvotes: 4
Reputation: 7489
You can select the child of a certain type of element by listing it after the parent type with a child selector (>). For example, you could find the nth child (any type) of an element with some class by using .someclass > *:nth-child(N)
, which will look in all .someclass
elements and find any element that is the nth-child(N)
.
It is important to note that you should use the child selector (>) rather than the descendant selector (simply a blank space) to ensure that it doesn't select the nth child of every child element (and their children, and theirs, etc.).
Note that older versions of IE and some other browsers do not support such selectors.
Upvotes: 1
Reputation: 4368
If you are selecting an element then you can use attribute and nth-child selectors on either the parent or the element itself:
section div:nth-child(1) { /*
any div that is a first child under the section
*/ }
.some_class > :nth-child(5) { /*
any element that is the fifth immediate child of .some_class
*/ }
section[title] > :nth-child(5) { /*
any element that is the fifth immediate child of a section tag
where the section tag has a title attribute
*/ }
Upvotes: 3
Reputation: 63830
Check out the W3 on attribute selectors.
E.g.
div[lang=nl] span {
color: red;
}
This will make all span
tags inside a <div lang='nl' />
color red.
I've made a fiddle here to see it in action.
Upvotes: 0