<!DOCTYPE HTML>
<
html
>
<
head
>
<
title
>
Find closest ancestor element that has a
specific class using pure JavaScript
</
title
>
</
head
>
<
body
style
=
"text-align:center;"
>
<
h1
style
=
"color:green;"
>
GeeksforGeeks
</
h1
>
<
p
id
=
"GFG_UP"
>
</
p
>
<
div
name
=
"parentDIV"
class
=
"parent"
>
<
div
class
=
"child"
>
</
div
>
</
div
>
<
button
onclick
=
"myGFG()"
>
click here
</
button
>
<
p
id
=
"GFG_DOWN"
>
</
p
>
<
script
>
var up = document.getElementById("GFG_UP");
up.innerHTML = "Click on button to see result";
var down = document.getElementById("GFG_DOWN");
function findParent(el, class) {
while ((el = el.parentNode) &&
el.className.indexOf(class) <
0
);
return el;
}
function myGFG() {
var
el
=
document
.querySelector(".child");
var
el
=
findParent
(el, 'parent');
down.innerHTML
=
"Element of name '"
+ el.getAttribute("name")
+ "' is the parent element of specific class.";
}
</script>
</
body
>
</
html
>