views:

3954

answers:

3

I'm trying to pass "this" from a clicked span to a jQuery function that can then execute jQuery on that clicked element's first child. Can't seem to get it right...

<p onclick="toggleSection($(this));"><span class="redClass"></span></p>

Javascript:

function toggleSection(element) {
  element.toggleClass("redClass");
}

How do I reference the :first-child of element?

+4  A: 

If you want to apply a selector to the context provided by an existing jQuery set, try the find() function:

element.find(">:first-child").toggleClass("redClass");

Jørn Schou-Rode noted that you probably only want to find the first direct descendant of the context element, hence the child selector (>). He also points out that you could just as well use the children() function, which is very similar to find() but only searches one level deep in the hierarchy (which is all you need...):

element.children(":first").toggleClass("redClass");
Shog9
thanks! works perfectly. I imagine the other ways listed below will work as well.
macca1
I believe `find()` searches through all descendants, and `:first-child` can match one element per parent. Hence, this query can is likely to return several elements. Or am I mistaken?
Jørn Schou-Rode
@Jørn: you're correct, I hadn't thought about this - if there is a hierarchy, then an unqualified :first-child selector will produce multiple results.
Shog9
+2  A: 

Have you tried

$(":first-child", element).toggleClass("redClass");

I think you want to set your element as a context for your search. There might be a better way to do this which some other jQuery guru will hop in here and throw out at you :)

theIV
+2  A: 

Use the children function with the :first selector to get the single first child of element:

element.children(":first").toggleClass("redClass");
Jørn Schou-Rode