Reputation: 3318
This is what I am trying to achieve (Consider this as an example scenario) -
Element 4 is my angular component. I would like to set its height based on the heights of Element 1 and Element 2.
Element 1 and Element 2 could be anywhere in the element hierarchy i.e. they don't necessarily have to be immediate parent or sibling. I would like to be able to get references of Element 1 and Element 2 by their class names and get their heights.
What is the best way to query for a parent element in angular by class name or any other selector?
Upvotes: 0
Views: 2999
Reputation: 1474
Just so you're aware, this isn't really a best practice type of approach. The Iteration happens 100 times hopefully looking for a parent element based on a class name.
/**
* findParentElementByClass, returns an parent element based on a
* class name. This parent class name is chained off the required
* child component.
*
* @param {String} parentClass // parent class
* @param {String} componentClass // Element 4 class in your case
* @return {Node} componentParent
*/
function findParentElementByClass(parentClass, componentClass) {
let componentParent = document.querySelector(`.${componentClass}`).parentNode;
for (let i = 0; i < 100; i++) {
if (componentParent.classList.contains(`.${parentClass}`)) {
break;
} else {
componentParent = componentParent.parentNode;
}
}
return componentParent;
}
Upvotes: 1
Reputation: 814
Have you tried to control height by CSS? like:
div p Selects all <p>
elements inside <div>
elements
div > p Selects all <p>
elements where the parent is a <div>
element
https://www.w3schools.com/cssref/css_selectors.asp
I'd recommend using classes though, like
element1-class > element4-class {
height: 30px;
}
Upvotes: 0