I do not know if "path" is the best definition. But using QuerySelector
you can get an element specifying a "path", such as:
main section.sobre .view-more
But how can I do the opposite?
If I have an element, such as <button class="view-more">
, how can I check to see if it is main section.sobre .view-more
?
The only way I found it would be to make a QuerySelector
and then compare this element with the current element:
window.document.addEventListener("click", function(e) {
[].forEach.call(window.document.querySelectorAll("main section.sobre .view-more"), function(el) {
if (el == e.target) {
window.console.log("Isso é o main section.sobre .view-more");
}
});
}, true);
<html lang="en">
<body>
<main>
<section class="sobre">
<button class="view-less">View Less</button>
<button class="view-close">View Less</button>
<button class="view-more">View More</button>
<button class="view-more">View More</button>
</section>
</main>
</body>
</html>
The problem is if you are searching for multiple "paths" you will have to execute multiple querySelectorAll
. That is, if you want to know if the element is main .a
, main .b
, main .c
, main .d
, you would have to querySelectorAll
to cad one, then compare. This is even worse if there are multiple elements with the same "path", as above, since it will have to iterate through querySelectorAll
itself.
This works, but it does not seem right to me. Is there another, more efficient, and native way to achieve this goal?