Reputation: 994
So I attach an event to the document to watch when a click event happens on a specific anchor with a class yui3-pjax
, in some instances the anchor has a span child element. How is it I can watch for just the click event bubbles to just the anchor? My current if-statement for watching the event is:
document.addEventListener('click', function(evt) {
if(evt.target.classList.contains('yui3-pjax') || evt.target.parentNode.classList.contains('yui3-pjax')) {
// do stuff
}
});
HTML snippets
<a class="page_current yui3-pjax" href="/forum/chatterbox/last-person-to-reply-wins/t.94028885_991/" title="page 67">
67
</a>
<a class="yui3-pjax cta-button-sm gray-button postitem-link pull-right" href="/forum/chatterbox/last-person-to-reply-wins/t.94028885_991/">
<span>67</span>
</a>
I'm not sure if there's a better way than watching both the anchor and the span element's parent (the same anchor) without binding it to the anchor itself, but the problem with that is some of the anchors are dynamically generated, and this
clearly won't work since it'll reference the document. Any ideas?
Edit: I think there's some confusion about what I'm asking. Let me clarify, I only want to have to check the anchor if it has the yui3-pjax class. I'm not sure how to handle the propagation/bubbling of the event from the child or descendant element of that anchor to achieve that.
Upvotes: 3
Views: 1494
Reputation: 6674
Hope I'm understanding this correctly. Instead of manually checking the element and the parent for a certain class, I would instead write a function that recurses up the DOM to find out whether the event target is contained within an element with the given class. This way, you don't have to write code that relies on the structure of the HTML, but that rather dynamically determines whether or not your element lives inside an element with (e.g.) class 'yui3-pjax'. Note I am not checking if the element with class 'yui3-pjax' is an anchor, but you can add that in if needed. Check out the fiddle http://jsfiddle.net/9L0jce6x/.
document.addEventListener('click', function(evt) {
if(elementOrParentsHaveClass(evt.target, 'yui3-pjax')){
//do stuff
}
});
//Recurse up the DOM until we find a parent with the given class, or return false if we don't
function elementOrParentsHaveClass(elem, className){
if(elem && elem.classList.contains(className)){
return true; //yay!
}else{
//Recurse only if parent exists
if(elem.parentNode){
return elementOrParentsHaveClass(elem.parentNode, className);
}
else{
//If the parent node does not exist, end recursion - we finished recursing up the DOM
return false;
}
}
}
Upvotes: 1