Javascript 中选定文本的节点名称
我的 HTML 看起来像这样:
<span id="text">
<span class="segment" id="first">some text</span>
<span class="segment" id="sec">bla bla</span>
</span>
当用户选择某些内容时,我想确定他选择了哪些元素。 例如,如果用户选择了“text bl”,我需要“first”和“sec”元素。
为此,我尝试使用 endContainer.nodeName 但对于每个选定的文本,我都会获得父元素“text”。是否可以获得子元素?
var selObj = window.getSelection();
var selRange = selObj.getRangeAt(0);
if(selRange!="") {
var startName = selRange.startContainer.nodeName;
var endName = selRange.endContainer.nodeName;
alert(startName+" "+endName);
}
I have HTML which looks something like this:
<span id="text">
<span class="segment" id="first">some text</span>
<span class="segment" id="sec">bla bla</span>
</span>
and when user selects something, I want to identify which elements he had selected.
If, for example, user had selected "text bl" I need both "first" and "sec" elements.
For this, I tried using endContainer.nodeName but for every selected text I get parent element "text". Is it posible to get child elements?
var selObj = window.getSelection();
var selRange = selObj.getRangeAt(0);
if(selRange!="") {
var startName = selRange.startContainer.nodeName;
var endName = selRange.endContainer.nodeName;
alert(startName+" "+endName);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在您的示例中,问题在于选择的开始和结束容器节点是文本节点。您可以通过检查
nodeType
属性来获取容器元素:...对于最终容器来说类似。
In your example, the problem is that the start and end container nodes for the selection are text nodes. You can get the container elements by checking the
nodeType
property:... and similar for the end container.