Understanding the DOM hierarchy in jQuery

I constantly come across strange things that I don't understand with jQuery and DOM identifiers and selectors. Usually I just walk around them, but I really want to do this once and for all. Consider the following markup:

<div id="accordionWrapper"><p><a class="expandall" href="#">Test</a></p></div> 

I have a jQuery click function on <a> :

 //works fine jQuery('a.expandall').click(function() {...whatever...}); 

But the following:

 //fails jQuery('#accordionWrapper p a.expandall').click(function() {...whatever...}); 

... which I do not receive. I don’t understand something about CSS or jQuery or ...?

+4
source share
3 answers

Actually, your understanding is not quite so. Here's a JsBin (JsFiddle doesn't seem to work) that shows your exact markup and your exact jQuery code, all work.

http://jsbin.com/inuqez/4/edit

So, if you are having problems with the second jQuery selector you gave, it should be something else. If you give us more details, we can help. Otherwise, just look carefully at your code and make sure that there are no obvious errors, for example, several elements with the same identifier (as @Frederic mentioned).

+5
source

Try:

 jQuery('div#accordianWrapper p a.expandall').click(...) 
0
source

First way:

 jQuery('a.expandall').click(function() {...whatever...}); 

... defines a click for any binding element with the "expandall" class that exists anywhere in the DOM.

The second way:

 jQuery('#accordionWrapper p a.expandall').click(function() {...whatever...}); 

... defines a click for any anchor with the class "expandall", which is a descendant of a paragraph element, which is a descendant of an element with id="accordionWrapper" . Note that the type of the "#accordionWrapper" element does not matter, since you did not specify it.

I say "element" with this id, not "element" with this id, because if your html is valid, there will be only one element with any given id. If you repeated the identifier for several elements, you will find that (for most browsers) the choice by id returns only one of these elements (most often the first).

Assuming your problem is with reusing identifiers, you can fix it by exposing several similar elements to the same class, rather than the same identifier.

0
source

All Articles