Gandalf StormCrow
Gandalf StormCrow

Reputation: 26222

Problems with jquery selector

I have a trouble with selecting element attributes with jquery here is my HTML:

<a class="myselector" rel="I need this value"></a>

<div class="someClass" id="someID">
...bunch of elements/content
<input type="button" name="myInput" id="inputID" title="myInput Title" />
...bunch of elements/content
</div>

...bunch of elements/content

Here I'm trying to get the rel value of myselector here is how I tried but its not working :

$('#inputID').live('click',function(){
console.log($(this).closest('a.myselector').attr('rel'));
});

Also tried this since all is wrapped in wrapper div :

$('#inputID').live('click',function(){
console.log($(this).parent('div.wrapper').find('a.myselector').attr('rel'));
});

I get undefined value in firebug in both cases, I use live because div#someID is loaded in the document its not there when page first loads. Any advice, how can I get my selector rel value?

EDIT:

However when I look for ('a.myselector') without rel attribute, I alert Object object and get console.log something []

Upvotes: 1

Views: 95

Answers (3)

karim79
karim79

Reputation: 342795

This should work:

console.log($(this).closest('div.wrapper').find('a.myselector').attr('rel'));

Your first example in your question does not work because the anchor tag you are trying to select is not a parent/ancestor:

console.log($(this).closest('a.myselector').attr('rel'));

Your second example would work if you changed .parent() to .parents(), as .parent() only traverses one level up the DOM, so the following:

console.log($(this).parents('div.wrapper').find('a.myselector').attr('rel'));

Upvotes: 3

Raja
Raja

Reputation: 3618

Please try this:

$('#inputID').live('click',function(){
  // alert($(this).parent().parent().html());
alert($(this).parent().parent().find('a.myselector').attr('rel'));
});

HTH

Upvotes: 0

Vnuk
Vnuk

Reputation: 2703

Just off the top of my head, have you tried accesing your rel value without using live (ie with direct id $("inputid").attr("rel") )?

I usually eliminate suspects one by one when faced with a problem like this.

Upvotes: 0

Related Questions