prashant kumar prashant kumar - 1 year ago 81
CSS Question

How to get the title of anchor tag which is inside a list and having class as selected

I have an unstructured list(

) inside
tags and I am trying to get the title of an anchor tag, which is inside an
that has

<div class="mainmenu">
<div class="mainmenulinks">
<li class="selected">
<a class="topmenu-navigation-links" id="topMenuItem0" href="" title="Private">
<span class="span-link-Private">Private</span>

<a class="topmenu-navigation-links" id="topMenuItem1" href="" title="Business">
<span class="span-link-Business">Business</span>

<a class="topmenu-navigation-links" id="topMenuItem2" href="" title="Broker">
<span class="span-link-Broker">Broker</span>

In this case, I should be getting Private as its

[Updated] Working Fiddle

Answer Source

You can use:


If you need to be more specific, you can add before the li, eg:

$(".mainmenu .mainmenulinks li.selected a").attr("title")

Your fiddle doesn't work as you've

  • not included jquery
  • not included "." for some classes (but have for others)
  • with hasClass, it needs to be in quotes without ".", eg .hasClass("selected")
  • tried to use this outside of a relevant context

Prop vs Attr

Summary of Preferred Usage

The .prop() method should be used for boolean attributes/properties and for properties which do not exist in html (such as window.location). All other attributes (ones you can see in the html) can and should continue to be manipulated with the .attr() method.

while prop does work and is an easy fall-back incase you're not sure which to use, it should be attr for title.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download