2

This is my code

<ul>
<li id="menu_house" class="main_menu "><a class="main_menu " href="searchHouse.php"><span>Houses</span></a></li>
<li id="menu_apartment" class="main_menu "><a class="main_menu " href="searchApartment.php"><span>Apartments</span></a></li>
<li id="menu_building" class="main_menu "><a class="main_menu " href="searchBuilding.php"><span>Buildings</span></a></li>
</ul>

I want to add a class to first <a> tag when page is loading, I know how to add menu_house <div>, like this:

$("#menu_house").addClass("selected");

How can I add a class to the <a> tag?

1
  • where is the problem? id are unique and you can add easily Commented May 30, 2011 at 10:03

5 Answers 5

2
$("#menu_house a").addClass("selected");
Sign up to request clarification or add additional context in comments.

Comments

1

In case you have multiple a tags with the main_menu class and you specifically want to add the class to the menu_house item:

$("#menu_house > a").addClass("selected");

2 Comments

This is actually the same as the accepted answer, only I answered it first. Oh well :(
this is also working. thank you very much. I'm very soory. this is my first question. I think I cant accept both.
1

Another approach would be:

$('ul li:first-child a').addClass('selected');

Comments

0

If #menu_house is always the first element use:

#("#menu_house a").addClass("selected");

If that's not the case use:

#("a.main_menu:first").addClass("selected");

Comments

0

You can also use the :first pseudo class Like

$('a.main_menu:first').addClass("selected");

Here is a demo http://jsfiddle.net/joycse06/geKFy/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.