简体   繁体   English

HTML / JS - 获取选定元素 class 和/或 ID

[英]HTML / JS - Get selected element class and/or ID

I am aware of how to use document.getSelection() to get the string of whatever text the user highlights.我知道如何使用document.getSelection()来获取用户突出显示的任何文本的字符串。

However, how do I access the class and/or id of the element from getSelection() ?但是,如何从getSelection()访问class和/或元素的id

Any thoughts?有什么想法吗?

I got your problem, Basically, the getSelection() method returns a Selection object representing the range of text selected by the user or the current position of the caret, You cant' get the class and id from the getSelection();我遇到了你的问题,基本上,getSelection() 方法返回一个选择 object 代表用户选择的文本范围或插入符号的当前 position,你不能从获取 ZA2F2ED4F8EBC2CBB4C21A29DCSelectionAB61; But, there are few ways to get class and id value from your HTML page to Javascript.但是,有几种方法可以从 HTML 页面获取 class 和 id 值到 Javascript。

  • First one, { For Class } const anything = document.getElementByClassName("Anything") ;第一个,{ For Class } const anything = document.getElementByClassName("Anything") ;
  • Second one, { For ID } const anything = document.getElementById("Anything") ;第二个, { For ID } const anything = document.getElementById("Anything") ;
  • Third one, For id and class... It will work on both - const selector = document.querySelector(".class #id") ;第三个,对于 id 和 class... 它适用于两者 - const selector = document.querySelector(".class #id") ;
  • A quick javascript snippet快速 javascript 片段
  • const cookies = document.getElementById("id-container") cookies.classList.toggle("active")

Follow, this strategy for selecting classNames and id instead of getSelection();按照这个策略选择 classNames 和 id 而不是 getSelection();

In the object which getSelection() returns you can find the focusNode .在 getSelection() 返回的 object 中,您可以找到focusNode focusNode includes the parentNode . focusNode 包括parentNode Inside that you can find the class and id which you are looking for.在里面你可以找到你正在寻找的 class 和 id。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM