General Question

Jakecanton's avatar

How can I write Jquery codes to select a certain element?

Asked by Jakecanton (3points) February 4th, 2010

I’m a foreigner, so please be patient when you are reading. Thank you! ^_^
I want to select a certain element and give it a class—“NewClass”, let’s say the element is a div with a class“Common”.

Here are the condition:
1.There are more than one div with the class “Common”, there might be 2,3, or 10 divs. But you have to know that not every div has the class “Common”.
2.The divs are wrapped by a father div that has a class “FatherDiv”.
3.I want to select the first div among those with the class “Common”.

Let me make it be more specific.HTML codes:
<html><body>
<div class=“FatherDiv”>
<div class=“OtherClass”>This is not I want to select.</div>
<div class=“Common”>OK, this div is the one I want to select and give it a new class-“NewClass”. </div>
<div class=“Common””>Though this div has the class “Common”, but it is the second div which has the class “Common”</div>
</div><!FatherDiv Ends>

<div class=“FatherDiv”>
<div class=“abc”>abc</div>
<div class=“Common”>I also want to select this div.</div>
<div class=“Common”>efg</div>
</div><!FatherDiv Ends>

</body></html>

So, I want to choose the the first div with the class “Common” in the “FatherDiv”. I hope you can understand what I am trying to express.

Of course, if those divs (with class “Common”) are warpped by a div that has a class “wrap”(in the mean time, divs without class “Common” are not included in “wrap” div), Jquery codes can be written easily:

$(document).ready(function() {
$(‘div.wrap div:first-child’).addClass(‘NewClass);
});

But I don’t want to add a div.

So, the question is how to write Jquery codes to make this work?

BTW:On answers.yahoo.com, a guy told to try“ $(‘div.FatherDiv div.Common:first’)”,it works well in the first “FatherDiv”.But it doesn’t work on the first “add” div in second “FatherDiv”.

Observing members: 0 Composing members: 0

3 Answers

andrew's avatar

Try $(‘div.FatherDiv div.Common:first-child’)

Jakecanton's avatar

dear andrew:
It still doesn’t work.

Vincentt's avatar

I do really think @andrew‘s answer should work, could you show a live example of your code? Perhaps the error is elsewhere.

Answer this question

Login

or

Join

to answer.

This question is in the General Section. Responses must be helpful and on-topic.

Your answer will be saved while you login or join.

Have a question? Ask Fluther!

What do you know more about?
or
Knowledge Networking @ Fluther