J-Cake
J-Cake

Reputation: 1618

Find node in Document

I have obtained a node through document.getSelection().anchorNode and I would like to view it as an element as though it were fetched by a query selector. Say my node is a p element containing the string hello world

<p>hello world</p>

The node appears in the DOM here:

<!doctype html>
<html>
    <head>
        <link rel="stylesheet" href="/master.css" />
    </head>
    <body>
        <p>hello world</p>
    </body>
</html>

I woudl like to get the <p> element from the document. But, a node that looks the same can appear several times, I would like to get the HTML element this node comes from.

Thanks

Upvotes: 0

Views: 1276

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1073968

Say my node is a p element containing the string hello world

Then anchorNode will be exactly the same object you'd get from querySelector.

But if it's the Text node within that p element, you'd want to use anchorNode.parentElement to access the p element.

Live Example:

var lastNode = null;
setInterval(function() {
  var selection = window.getSelection();
  var node = (selection && selection.anchorNode) || null;
  if (node === lastNode) {
    return;
  }
  lastNode = node;
  if (!node) {
    console.log("(No selection)");
  } else {
    var result = "Node name is " + node.nodeName;
    if (node.nodeType === 3) { // Text
      console.log(result, "parent element:", node.parentElement);
    } else {
      console.log(result);
    }
  }
}, 250);
Select some text, an analysis of <code>window.getSelection().anchorNode</code>'s result will appear in the console.
<p>hello world</p>

Upvotes: 1

Related Questions