Skip to main content
Known Participant
February 28, 2007
Question

How To Traverse Nodes of Selected Text

  • February 28, 2007
  • 2 replies
  • 429 views
In Code View, when a user selects/highlights some text and executes my custom action i would like to get to the text's top level element.

a simple example:
the text in code view looks like this to the user:
<html>
<body>
<p><font>my text</font></p>
</body>
</html>

In the above example i am trying to get to the <p> tag. here is the code (in its simplest form for ease of use) that i am using:
var dom = dw.getDocumentDOM();
var theSelection = dom.getSelectedNode();
if (theSelection.nodeType == Node.TEXT) {
dom.setSelectedNode(theSelection);
dom.source.selectParentTag(); --> this would be the <font> tag
dom.source.selectParentTag(); --> this would be the <p> tag
var test = dom.getSelectedNode();
alert(test.tagName); --> i would expect this to be the <p> tag, but it always seems to be the <font> tag
}

when looking at the text in Code View, everything is selected correctly all the way up to the <p> tag, but when i get the selected node and alert its tag name, it still seems to be set at the <font> element. my code doesnt seem to recognize that i am at the <p> tag element.

any suggestions?
This topic has been closed for replies.

2 replies

March 1, 2007
Perhaps a different approach. Use a while statment to back up until you are certain that you have an Element node (a tag). If you already have an Element selected then it works, if not it traces the parents up the tree until you have one (though it should be the next node in the tree, the while forces it to work in any case).

Consider this:
var dom = dw.getDocumentDOM();
var selnode=dom.getSelectedNode()
if (selnode.nodeType==Node.DOCUMENT_NODE) {
selnode=selnode.body
} else if (selnode.nodeType!=Node.ELEMENT_NODE) {
while ((selnode.parentNode) &&
((selnode.nodeType==Node.TEXT_NODE) || (selnode.nodeType==Node.COMMENT_NODE))) {
selnode=selnode.parentNode
}
}
if (selnode.nodeType!=Node.ELEMENT_NODE) {
//this is an error - empty document with no nodes
return
}
alert(selnode.tagName)
Inspiring
March 1, 2007
And this ?

var dom = dw.getDocumentDOM();
var theSelection = dom.getSelectedNode();
if (theSelection.nodeType == 3) {
dom.setSelectedNode(theSelection.parentNode);
dom.setSelectedNode(dom.getSelectedNode().parentNode);
var test = dom.getSelectedNode();
alert(test.tagName);
}