Opened 11 years ago
Closed 11 years ago
#10213 closed enhancement (duplicate)
[cla] Searching the Ancestor Hierarchy for the first DOMNode.nodeName
Reported by: | ole | Owned by: | sjmiles |
---|---|---|---|
Priority: | high | Milestone: | tbd |
Component: | HTML | Version: | 1.4.0b |
Keywords: | Cc: | [email protected]… | |
Blocked By: | Blocking: |
Description (last modified by )
/** * Returns the first ancestor node found that has the * parentNodeName argument as the DOMNode.nodeName. */ findAncestorNodeByName: function(/*String*/ ancestorNodeName, /*DOMNode*/ domNode) { var ancestorNode = domNode.parentNode; if (ancestorNode && ancestorNode.nodeName.toLowerCase() == ancestorNodeName.toLowerCase() ) { return ancestorNode; } return ancestorNode && this.findAncestorNodeByName(ancestorNodeName, ancestorNode); }
Change History (5)
comment:1 Changed 11 years ago by
Component: | General → HTML |
---|---|
Description: | modified (diff) |
Owner: | changed from anonymous to sjmiles |
Summary: | [Contribution] Searching the Ancestor Hierarchy for the first DOMNode.nodeName → [cla] Searching the Ancestor Hierarchy for the first DOMNode.nodeName |
comment:2 Changed 11 years ago by
Description: | modified (diff) |
---|
Fixing obvious bugs in the code keeping it recursive and with this
.
comment:3 Changed 11 years ago by
The original code works for me, but I code all utility functions on classes and use them only on other classes as mixins. I was thinking that that using the this keyword would be OK here, since there's no delegation to other objects until the function completes...But I'm not crazy about it either :).
comment:4 Changed 11 years ago by
Per discussion with Peter, Ben, and Les this does the job:
/** * Returns the first ancestor node found that has the * parentNodeName argument as the DOMNode.nodeName. */ findAncestorNodeByName: function(/*String*/ ancestorNodeName, /*String*/ domNodeID) { return dojo.query("#" + domNodeID).parents(ancestorNodeName)[0]; }
Note that dojo.query("#" + domNodeID).closest(ancestorNodeName)[0] will also work, but I'm assuming "parents" is better, because the intention is to search ancestors and I think closest also looks at siblings, etc.
Also there's a similar function in dijit (dijit.range.getAncestor(..) ). It would be great if these were grouped under something like dojox.html.search...
comment:5 Changed 11 years ago by
Resolution: | → duplicate |
---|---|
Status: | new → closed |
To clarify, closest() only looks at parent elements, not siblings. The difference between closest and parents is that closest considers the current node in the query. In this case, parents() is correct to use.
So given that there is a function already that supports this function via dojo.NodeList?-traverse's parents() call, I am going to close this ticket.
Probably simpler (and more efficient) to do it using a loop rather than a straight recursion. As is the code doesn't work. And it uses
this
, which we try to avoid.