Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get title attribute with jQuery

I have a jQuery Mobile accordion menu set up like:

<div class="subCat" data-role="collapsible">
    <h3 title="someTitle">Subcategory Name</h3>
    <div class="itemImg">
        <img alt="Item 1" src="[image location]" /><span>Item 1</span>
    </div>
    <div class="itemImg">
        <img alt="Item 1" src="[image location]" /><span>Item 1</span>
    </div>
</div><!--End of subCat-->

Which goes on for several subcategories. I have a bit of code to get both the subcategory name and the title attribute from the image when clicked.

var currCat=$(this).closest('.subCat').children('h3').text();
var titleData=$(this).closest('.subcat').children('h3').attr("title");

"this" being the image that's clicked. currCat gets the proper string that it needs, but I'm always getting "undefined" for titleData. Not sue what's going wrong with getting the title.

like image 609
user1238565 Avatar asked May 07 '12 22:05

user1238565


People also ask

How to get attribute name in jQuery?

To get the name, you'd use $(selector). attr('name') which would return (in your example) 'xxxxx' .

How to get a value of an attribute in jQuery?

jQuery attr() Method The attr() method sets or returns attributes and values of the selected elements. When this method is used to return the attribute value, it returns the value of the FIRST matched element.

How to add attribute using jQuery?

You can add attributes using attr like so: $('#someid'). attr('name', 'value'); However, for DOM properties like checked , disabled and readonly , the proper way to do this (as of JQuery 1.6) is to use prop .

How do you check if an element has an attribute in jQuery?

Using jQuery The idea is to use the . attr() method, which returns the attribute's value for an element if it is present and returns undefined if the attribute doesn't exist.


1 Answers

Your second line has subcat instead of subCat. The following should work:

$(this).closest('.subCat').children('h3').attr("title");

Thank you for reminding me that classNames are case-sensitive in selectors. Easy thing to miss.

like image 150
Sampson Avatar answered Sep 17 '22 17:09

Sampson