From the course: JavaScript: Enhancing the DOM

Unlock the full course today

Join today to access over 24,000 courses taught by industry experts.

Traversing with closest and contains

Traversing with closest and contains

From the course: JavaScript: Enhancing the DOM

Traversing with closest and contains

- [Instructor] In this video we're focusing on two methods of DOMs reversal, closest and contains. Closest is like a detective. It looks up through the dormitory and finds the nearest ancestor that matches a given selector. Here you can see an example. We are getting an element with ID news content, and then we are looking for the nearest ancestor with the class article. Here we have our HTML. On line 22, we have a paragraph with ID news content, and now we're going to look for the nearest ancestor with the class article, you can probably figure it out. And let's see if indeed that is what happens. So I'm going to run this code, and as you can see, it finds the closest article. It's around the paragraph with ID news content. On the flip side, contains checks if a node is a descendant of another node, it's a bit like asking, are you my child? Here you can see an example. We select the element with ID main content, and we're then going to see whether main content contains news content…

Contents