In my code I am using querySelectorAll
to create a nodeList.
var a = document.querySelectorAll('tbody > tr.editable:not(.empty-bench)')
This array contains ~17 elements and I want to be able to filter these results where the childNode has a certain class.
I am currently using a[0].childNodes
but this just displays all the children. I only want it to return the specific ones that contain a class .P-xs
In my code I am using querySelectorAll
to create a nodeList.
var a = document.querySelectorAll('tbody > tr.editable:not(.empty-bench)')
This array contains ~17 elements and I want to be able to filter these results where the childNode has a certain class.
I am currently using a[0].childNodes
but this just displays all the children. I only want it to return the specific ones that contain a class .P-xs
-
tbody > tr.editable:not(.empty-bench) > .P-xs
? – John Bupit Commented Sep 6, 2015 at 22:31 -
querySelectorAll
returns aNodeList
ornull
, never anArray
. – Oriol Commented Sep 6, 2015 at 22:36 -
Not sure if I understand, but try
querySelectorAll('tbody > tr.editable:not(.empty-bench).P-xs')
– Oriol Commented Sep 6, 2015 at 22:38 - The problem is that before I go into the childNodes of my querySelector, I want to save something to a variable. Then I want to go into P-xs – Bijan Commented Sep 6, 2015 at 22:39
-
Is that
P-xs
class in thetr
or in thetd
? – Buzinas Commented Sep 6, 2015 at 22:42
4 Answers
Reset to default 8According to this, you should be able to then call a[0].querySelectorAll('.P-xs')
You can use Function.prototype.call
to borrow Array.prototype.filter
and be able to use it on your NodeList
:
var a = document.querySelectorAll('tbody > tr.editable:not(.empty-bench)');
var b = [].filter.call(a, function(el) {
return el.classList.contains('P-xs');
});
You can use a for loop on your initial query selector result to create an array only containing those elements with a given descendant. See the example below.
var a = document.querySelectorAll('#one');
var b = [];
for (var i = 0; i < a.length; i++) {
if (a[i].querySelectorAll('#two').length) {
b.push(a[i]);
}
}
b.forEach(function (item, i, array) {
item.style.color = 'red';
});
<div id="one">
One
</div>
<div id="one">
<div id="two">Two</div>
</div>
If you're seeking for childNode
contains P-xs
class then try this. It will return array of all child nodes have that class.
var a = document.querySelectorAll('tbody > tr.editable:not(.empty-bench)');
var afterFilter = [].concat.apply([], [].map.call(a, function (el) {
return [].filter.call(el.childNodes, function (ch) {
return ch.nodeType === 1 && ch.classList.contains('P-xs');
});
}));
But if you want the parent then try below:
var a = document.querySelectorAll('tbody > tr.editable:not(.empty-bench)');
var afterFilter = [].map.call(a, function(el) {
return [].filter.call(el.childNodes, function (ch) {
return ch.nodeType === 1 && ch.classList.contains('spec');
});
});