tags:

views:

43

answers:

3

I feel dumb.. Why is my "header" div not being selected? Its background color is not being changed. I am learning about the + operator so I am not looking for a different selector.

E + F : an F element immediately preceded by an E element

In this case the div tag is immediately preceded by the div with id divA but it is not selected.

$("#divA + div").css("background-color", "red");

Html

<div id="divA">
        <div>
            Header</div>
        Lorem Ipsum is simply dummy text of the 
        printing and typesetting industry.
</div>

Thanks!

+5  A: 

You want:

$("#divA > div").css("background", "red");

> is the child selector. It's saying find me all <div> elements that are direct children of the element with ID of divA. When you write $("#divA + div") you're saying "find me the <div> that immediately follows the <div> with ID divA. + means "next sibling".

To clarify:

<div id="divA">
  <div>child</div>
</div>
<div>next</div>

So:

$("#divA > div") // child
$("#divA + div") // next
cletus
Why does the + operator not work in this case?
rkrauter
@rkrauter because the inner div is a child not a sibling.
cletus
not correct. "find me the `<div>` that immediately follows the *sibling* `<div>` with ID `divA`"
ghoppe
@ghoppe hows that not what I said?
cletus
@cletus looks good after your clarification. I don't think i saw your last sentence there when i first posted.
ghoppe
So to find the very first decendant, I would do $("#divA > div:first"), correct? Thanks in advance.
rkrauter
@rkrauter: Yep this should do it.
Felix Kling
Thank you Felix!
rkrauter
+1  A: 

E + F is an F element immediately preceded by a sibling E element.

Your header div is a child element of your #divA element.

ghoppe
+1 @OP: More: http://www.w3.org/TR/2009/PR-css3-selectors-20091215/#sibling-combinators
T.J. Crowder
+1  A: 

E + F an F element immediately preceded by an E element means that it will select F if E is the preceding sibling.
E.g. your HTML would have to look like this in order to make the selector work:

<div id="divA">
        Lorem Ipsum is simply dummy text of the 
        printing and typesetting industry.
</div>
<div>Header</div>

Otherwise you have to use a child or descendant relationship:

$('#divA div').css("background-color", "red");
Felix Kling