gpt4 book ai didi

javascript - 在文档中查找节点

转载 作者:行者123 更新时间:2023-12-03 00:32:25 25 4
gpt4 key购买 nike

我通过document.getSelection().anchorNode获得了一个节点我想将其视为一个元素,就好像它是由查询选择器获取的一样。假设我的节点是 p包含字符串 hello world 的元素

<p>hello world</p>

节点出现在 DOM 中:

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

我想获得<p>文档中的元素。但是,看起来相同的节点可能会出现多次,我想获取该节点来自的 HTML 元素。

谢谢

最佳答案

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

然后 anchorNode完全与您从 querySelector 获得的对象相同。

但是,如果它是 p 元素内的 Text 节点,您需要使用 anchorNode.parentElement 来访问 p 元素。

实例:

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>

关于javascript - 在文档中查找节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53801659/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com