0

I'm trying to determine if an element is a descendant of another elect that has a specific attribute. So far, I have no issue when the value is true, but I get TypeError: undefined is not a function (evaluating 'node.hasAttribute(attribute)') when hasAttribute is false. Any ideas?

document.body.addEventListener('touchmove', function(event) { stopScroll(event); });
var stopScroll = function(event) {
    var target = event.target;
    var parent = target.parentNode;

    if (isDescendantOf.attribute('data-scroll', target)) {

    } else {
        event.preventDefault();
    }
};
var isDescendantOf = {};
isDescendantOf.parent = function(parent, child) {
    var node = child.parentNode;
    while (typeof node !== 'undefined') {
        if (node == parent) {
            return true;
        }
        node = node.parentNode;
    }
    return false;
};
isDescendantOf.tag = function(tag, child) {
    var node = child.parentNode;
    while (typeof node !== 'undefined') {
        if (node.tagName == tag) {
            return true;
        }
        node = node.parentNode;
    }
    return false;
};
isDescendantOf.attribute = function(attribute, child) {
    var node = child.parentNode;
    while (node !== null) {
        console.log(typeof node);
        if (node.hasAttribute(attribute) === true) {
            return true;
        }
        node = node.parentNode;
    }
    return false;
};

Here's the fiddle, though it acts even weirder for some reason: http://jsfiddle.net/x95tgmkn/

CJT3
  • 2,788
  • 7
  • 30
  • 45
  • Try using parentElement or check the type of the node for text vs element – Mouser Jan 19 '15 at 12:30
  • @Mouser I had tried doing that with `typeof node === 'object'` in the other functions, tried changing it to `node !== null` but still the same issue. Is there another way to check if it's an element?' – CJT3 Jan 19 '15 at 12:35
  • After a quick google, `node instanceof HTMLElement` appears to be the way to go. Thanks for the nudge in the right direction! – CJT3 Jan 19 '15 at 12:39
  • Using parentElement ignores textnodes – Mouser Jan 19 '15 at 13:16

1 Answers1

0

Your loop goes from the child.parentNode up to the document, and on each node it uses the hasAttribute method of the Element interface. However, Documents are plain Nodes that do not implement this interface.

Change your condition to

while (node != null && node.nodeType == 1)

or node.nodeType != 9 or typeof node.hasAttribute == "function".

Bergi
  • 630,263
  • 148
  • 957
  • 1,375