dazz
dazz

Reputation: 8742

Jquery start search in self

I currently use the folowing:

var element = $('#Adiv').find('[name="thename"]');

This searches in Adiv for an element with the name 'thename'. But Adiv could also have the name 'thename', so it should first look at its own name. How do I do this? I tried andSelf(), but that just includes the entire element even if it doesn't have the right name.

Upvotes: 2

Views: 227

Answers (3)

Noyo
Noyo

Reputation: 5134

For your case, just change the selector and drop the find:

var $element = $('#Adiv[name="thename"], #Adiv [name="thename"]');

This will result in a jQuery object containing Adiv (if it matches), and any children of Adiv that match.

An alternative, more performant approach if you use jQuery >= 1.4 and know Adiv is definitely there in the DOM:

$('#Adiv').filter('[name="thename"]').add('[name="thename"]', window.Adiv);

...though I'd recommend the first one, as it's a bit cleaner and more resilient.

Upvotes: 0

Dr.Molle
Dr.Molle

Reputation: 117334

This may be an option, as an ID is unique:

$('#Adiv').find('*[name="thename"]').add($('#Adiv[name="thename"]'));

Upvotes: 0

Andy
Andy

Reputation: 30135

you could do something like this:

var element = $('#Adiv').parent().find('[name="thename"]');

Upvotes: 4

Related Questions