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
Since textNodes do not have any attributes you will have to get the attributes from the element parent. The select event
has spotty 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:
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
.)
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.
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>