Is there any DOM method to find the first element that has a certain class
<div >
<div>
<div></div>
<p ></p>
</div>
</div>
what if i have multiple p elements in the page and i need only to find the p element that is anywhere in the subtree starting from .parent
.
CodePudding user response:
document.querySelector('.parent p.paragraph')
Will return at most one p
element with the paragraph
class that has an element with the parent
class as an ancestor. It may return undefined
if there are no elements matching that description. If there are multiple that match that description, it will return only one, the “first” as JavaScript defines it. Whether JavaScript’s idea of the “first” is the same as yours or not it’s unclear, since you haven’t defined which would be “first” in your question. As MDN puts it,
Note: The matching is done using depth-first pre-order traversal of the document's nodes starting with the first element in the document's markup and iterating through sequential nodes by order of the number of child nodes.
That means if you have this
var paragraph = document.querySelector('.parent p.paragraph');
console.log(paragraph.innerText);
<div >
<div>
<div>
<div>
<p >First</p>
</div>
</div>
</div>
<p >Second</p>
</div>
It will print “First” in the console, not “Second,” as that element is the one paragraph
is set to because querySelector
searches down through the div
s first (depth-first).
CodePudding user response:
const parents = document.querySelectorAll('.parent');
if (parents) {
parents.forEach((parent, index) => {
const children = parent.querySelectorAll('.paragraph');
children[0].style.color='#f00';
children[0].style.textDecoration = 'underline';
console.log((children ? children.length : 'No') ` instances of paragraph class in parent ${index}`);
});
} else {
console.warn('no soup for you.')
}
// Or if you're just wanting to grab them all in one.
const parents2 = document.querySelectorAll('.parent .paragraph');
console.log(`There's ${parents2.length} instances of .parent .paragraph class in the document total.`);
console.log(`The first instance found is ${parents2[0]}`);
<div >
<div>
<div></div>
<p >TEST</p>
</div>
<div>
<div></div>
<p >TEST</p>
</div>
<div>
<div></div>
<p >TEST</p>
</div>
<div>
<div></div>
<p >TEST</p>
</div>
</div>
<div >
<div>
<div></div>
<p >TEST2</p>
</div>
<div>
<div></div>
<p >TEST2</p>
</div>
<div>
<div></div>
<p >TEST2</p>
</div>
</div>