I’m trying to fill an array with all direct child elements of a div.
example:
<div>
<span></span>
<a></a>
</div>
should result in an array containing span and a
How Would I achieve this?
I tried var elements = $('.thediv').children(); but that doesn’t seem to work.
Also how Would I then use that information for this kind of function?:
$(“element1″,”element2″,”element3”) depending on the result of the array?
Really thank you for your help! I am kind of lost with this thing
Note: I’m using zepto.js which has a similar syntax to jquery but misses a lot of functions so that might be a problem but I am also happy with solutions using jquery syntax because it should work pretty well 🙂 https://github.com/madrobby/zepto
To get the tags into the array, you could easily use, with jQuery (though I’m unfamiliar with zepto):
JS Fiddle demo.
And to use them, you can try:
JS Fiddle demo.
Although this simply uses the
tagNameof each element, so if there is more than oneawithin the relevant element all elements matching the selector, effectively$('div').find('a')in this case, will be targeted by the selector.The above caution seems to be discounted through use of a more complicated selector, and behaviour, and allows for each element to be iterated over one at a time, though I can’t help but feel it’s a little more complex than it needs to be:
JS Fiddle demo.
Sigh, I’m an idiot. The final iteration of this is below, which reduces the complexity somewhat, and allows for proper iteration over each element according to their position in the array:
JS Fiddle demo.
Having said the above, though, if you want to “target all elements within,” why not simply target those elements with:
Which will select, and target, each direct child of the
divelement without first holding them in, or having to hold them in, a user-created array variable.