简体   繁体   中英

Get Attributes of window.getSelection().anchorNode

window.getSelection().anchorNode returns quite a lot of details about the node where the user clicked to start the selection, but how can I get attributes of that text node, like class , id etc.?

Example:

<span id="word1">Aaa</span>
<span id="word2">Bbb</span>

The user selects something of these two spans and I need to know where he started the selection, whether in #word1 or in #word2

guess you need this: window.getSelection().anchorNode.parentNode

 window.onclick = function() { console.log(window.getSelection().anchorNode.parentNode) console.log(window.getSelection().anchorNode.parentNode.className); console.log(window.getSelection().anchorNode.parentNode.id) }
 <p class="cls" id="p1">p tag with class="cls" and id="p1",try to select something</p>

Since textNodes do not have any attributes you will have to get the attributes from the element parent. The select event has spoty support so I used the mousedown event and registered the Document Object to listen for it. In order to control where and when you get values from among 100 possibilities (remember the Document Object will be aware of mousedown event on anything but the Window Object), we must establish 2 things:

  1. Event.currentTarget: A property of the Event Object , that represents the element registered to the event. In the Demo e.currentTarget is the Document Object ( document .)

  2. Event.target: A property of the Event Object that represents the origin of an event, which is fancy talk for the element that was clicked, changed, hovered over, etc. In the Demo e.target is basically anything in the document .

The following Demo demonstrates a way to get the id and/or classes of a clicked element node.

Demo

Details are commented in Demo

 document.addEventListener('mousedown', showAttr, false); function showAttr(e) { // if the node clicked is NOT document... if (e.target !== e.currentTarget) { /* if the clicked node has a class attribute... || log all of its classes in console */ var tgt = e.target; if (tgt.hasAttribute('class')) { var cList = tgt.classList; console.log('class=' + cList); } /* if the clicked node has an id... || log its id in console */ if (tgt.hasAttribute('id')) { console.log('id=' + tgt.id); } } return false; }
 .as-console-wrapper { width: 30%; margin-left: 70%; min-height: 100%; } main, main * { outline: 1px solid black }
 <main id='base'> <h1 class='mainHeading'>Title</h1> <ol class='ordered list'> <li class='1'>One</li> <li class='2'>Two</li> <li class='3'>Three</li> </ol> Text <article id='post31' class='test'> <h2 class='postHeading'>Title</h2> <p class='content text'>Post content</p> article text </article> </main> </main>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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