[英]How can I extract the className from a span that is selected using javascript?
I have this HTML: 我有这个HTML:
<span class="redColor">gold</span>
And when I have the text selected that is within the span tags, I need to be able to somehow extract the className from the span using javascript. 当我选择了span标签内的文本时,我需要能够以某种方式使用javascript从span中提取className。 I don't know anything about the class in advance, only that it will be in a span, and the text will be selected.
我事先对这个课程一无所知,只是它会在一个范围内,并且会选择文本。
I assume you mean Text selected with the mouse or the keyboard? 我假设您的意思是用鼠标或键盘选择文本? You can access that with
您可以访问它
window.getSelection()
Then you can work your way up the DOM tree: 然后你可以在DOM树上工作:
window.getSelection().anchorNode.parentNode.className
See https://developer.mozilla.org/en-US/docs/Web/API/Selection.anchorNode for documentation of the Selection class 有关Selection类的文档,请参阅https://developer.mozilla.org/en-US/docs/Web/API/Selection.anchorNode
Use className
property. 使用
className
属性。
Example: 例:
var x = document.getElementsByTagName('span');
document.write("Body CSS class: " + x.className);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.