JQuery starts searching in its own

I am currently using the following:

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

It searches in Adiv for an element named "thename". But Adiv may also have the name "thename", so it must first look at its name. How can I do it? I tried andSelf() , but it just includes the whole element, even if it does not have the correct name.

+2
jquery
source share
3 answers

you can do something like this:

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

This may be an option because the identifier is unique:

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

In your case, just change the selector and omit find :

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

This will lead to the creation of a jQuery object containing Adiv (if one matches), and any Adiv children that match.

An alternative, more efficient approach if you use jQuery> = 1.4 and know that Adiv definitely exists in the DOM:

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

... although I would recommend the first, as it has become cleaner and more sustainable.

0
source share

All Articles