开发者

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="im开发者_C百科gholder" 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=


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


$("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/


$('.sort span')

Did I misunderstand?


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/


find() finds elements within a given element.

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜