LearnFrenzy
Sign in Take a free test

DOM Manipulation · Predict the Output · Question 11

closest from a nested element Answer, explanation & discussion

  • Output
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 11 Back to Exercise

The page contains this HTML:

<ul id="cart"><li data-sku="PEN-01"><span>Pen</span> <button>Remove</button></li></ul>

What does the following JavaScript code print when it runs on this page?

main.js
const btn = document.querySelector("#cart button");
console.log(btn.closest("li").dataset.sku, btn.closest("#cart").id, btn.closest(".missing"), btn.closest("button") === btn);
  • A PEN-01 cart undefined false
  • B PEN-01 cart null true Correct
  • C undefined cart null true
  • D PEN-01 null null true
Correct Answer: Option B

closest checks the element itself first, then its ancestors, and returns null when nothing matches.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links