I need to rewrite a function (in Javascript) so it checks to see if a parent exi
ID: 3809387 • Letter: I
Question
I need to rewrite a function (in Javascript) so it checks to see if a parent exists for an element. If it doesn't exist, I'll console log a string. I'm assuming I need to use .parentNode or .parentElement, just not sure how to implement it. Here is the function I need to rewrite:
var findParentByClassName = function(element, targetClass) {
if (element) {
var currentParent = element.parentElement;
while (currentParent.className !== targetClass && currentParent.className !== null) {
currentParent = currentParent.parentElement;
}
return currentParent;
}
};
Explanation / Answer
Here is code:
var findParentByClassName = function (element, targetClass) {
if (element) {
var currentParent = element.parentElement;
while (currentParent !== null) { // check if reached to end
if (currentParent.className == targetClass) // if matches
return currentParent; // return current node
currentParent = currentParent.parentElement; // find parent
}
console.log("not found"); // if not found
}
};
Sample program to test:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script>
var findParentByClassName = function (element, targetClass) {
if (element) {
var currentParent = element.parentElement;
while (currentParent !== null) { // check if reached to end
if (currentParent.className == targetClass) // if matches
return currentParent; // return current node
currentParent = currentParent.parentElement; // find parent
}
console.log("not found"); // if not found
}
};
</script>
</head>
<body>
<div class="test">
<div>
<div>
<input type="button" name="name" value="Click me" />
</div>
</div>
</div>
</body>
</html>
Output in cosole log:
not found