PruitIgoe
PruitIgoe

Reputation: 6384

Get attribute of child element

If I have the following markup:

<p class="header hours">
    <a href="javascript:void(0)" class="sort" sortcat="hours">
        Hours&nbsp;<span class="imgholder" sortcat="hours">&nbsp;</span>
    </a>
</p>

How can I target the <span> tag within the anchor tag? There are five other similar <p> tag entries, each with a different value for sortcat=

Upvotes: 29

Views: 102376

Answers (5)

TJ Kirchner
TJ Kirchner

Reputation: 4321

There's a couple of ways you can reference the span tag, but all of them end with " .attr('sortcat'); " I guess it depends on how specific you want to be and how flexible you need to be if there's a few other p tags with anchor tags and spans inside.

$('p.header a.sort span.imgholder').attr('sortcat');

/* or */

$('span.imgholder').attr('sortcat');

You can select elements based upon their tag name, their class name, or by the attributes inside the tags. Refer to jQuery's documentation on selectors:

http://api.jquery.com/category/selectors/basic-css-selectors/

http://api.jquery.com/category/selectors/

Upvotes: 1

Brian Donovan
Brian Donovan

Reputation: 8390

$("a span[sortcat]").attr('sortcat')

That'll give you the first element's sortcat value. To get all of them, do this:

$("a span[sortcat]").map(function(){ return $(this).attr('sortcat') })

See this working demo: http://jsfiddle.net/BwgDW/

Upvotes: 11

scragz
scragz

Reputation: 6690

find() finds elements within a given element.

$('a.sort').find('span');

Upvotes: 0

mkoryak
mkoryak

Reputation: 57928

$(".sort").click(function(){
  var cat =  $(this).children("span").attr("sortcat");
  //do something with the sortcat
});

Upvotes: 59

sdleihssirhc
sdleihssirhc

Reputation: 42496

$('.sort span')

Did I misunderstand?

Upvotes: 3

Related Questions