Peter
Peter

Reputation: 1

jQuery get nested <a> element attribute inside div element

The object on the page

<DIV style="TEXT-INDENT: 0px; VISIBILITY: inherit" id=button46 jQuery16107163179349561973="2">
    <A title=Exit href="javascript:void(null)" name=button46anc>
        <IMG style="CURSOR: pointer" border=0 name=button46Img alt=Exit src="images/btn-exitoff.gif" width=66 height=39>
    </A>
</DIV>

I need to get the value of the title attribute from the div.

Put a few hours into this with no luck (all return undefined)

$('div [id^="button"]').bind('click mouseover mouseout submit',function(event){
    testThis = $(this.children('a'));alert($(testThis).attr('title'));
    testThis2 = $(this.find('a'));alert($(testThis2).attr('title'));
});

Thanks in advance for saving th rest of my hair.

Upvotes: 0

Views: 6317

Answers (3)

jfriend00
jfriend00

Reputation: 707476

You need to turn this into a jQuery object before you can use jQuery functions on it.

$('div [id^="button"]').bind('click mouseover mouseout submit',function(event){
    alert($(this).find('a')).attr('title'));
});

Upvotes: 0

jk.
jk.

Reputation: 14435

$('div[id^="button"]').bind('click mouseover mouseout submit', function(event) {
    testThis = $(this).children('a');
    alert(testThis.attr('title'));
});

Upvotes: 3

Guffa
Guffa

Reputation: 700402

The contents of this is not a jQuery object, it's a DOM element. Wrap it in a jQuery object to use the children and find methods, and then you don't need to wrap the result:

$('div [id^="button"]').bind('click mouseover mouseout submit',function(event){
  var testThis = $(this).children('a'); alert(testThis.attr('title'));
  var testThis2 = $(this).find('a'); alert(testThis2.attr('title'));
});

Also, declare the variable locally, so that they don't end up in the global namespace.

Another variation is to use the DOM element as context for a search:

var testThis = $('a', this);

Upvotes: 0

Related Questions