Tuesday, June 4, 2024
 Popular · Latest · Hot · Upcoming
191
rated 0 times [  197] [ 6]  / answers: 1 / hits: 17436  / 11 Years ago, mon, april 1, 2013, 12:00:00

I'm having trouble getting a selector to work properly.



I have this HTML:



<div.wrapper>
<div.ui-controlgroup-controls>
<form>
<div.ui-btn></div>
</form>
<div.ui-btn></div>
<div.ui-btn></div>
<div.ui-btn></div>
<div.ui-btn></div>
</div>
</div>


and I'm trying to select the div tags, which are children of ui-controlgroup-controls - which means excluding whats inside the form.



This is what I'm trying:



// el is my div.wrapper element
el.children[0].getElementsByTagName(div);


However this does not work, because the div inside the form ends up in the selection.



Question:

How can I select the elements correctly when I don't want to use jQuery?


More From » selection

 Answers
16

One way to do this is to iterate over your resulting node list and check the parent:



var nodes = el.children[0].getElementsByTagName(div);
nodes = Array.prototype.slice.call(nodes);
nodes = nodes.filter(function(v, i){
return v.parentElement === el.children[0];
});


Here is a demonstration of this approach: http://jsfiddle.net/WLhY2/



A simpler (albeit less efficient) approach is to use querySelectorAll to retrieve the relevant nodes using a selector expression:



var divs = document.querySelectorAll('div.ui-controlgroup-controls > div')

[#79184] Sunday, March 31, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jaleelh

Total Points: 661
Total Questions: 125
Total Answers: 103

Location: Sweden
Member since Mon, May 8, 2023
1 Year ago
jaleelh questions
Tue, Feb 23, 21, 00:00, 3 Years ago
Tue, Jan 19, 21, 00:00, 3 Years ago
Wed, Aug 26, 20, 00:00, 4 Years ago
Mon, Jul 27, 20, 00:00, 4 Years ago
;