Get the node where you write


Get the node where you write



I want to get the node where the cursor is when it is being written




document.getElementById('parent').addEventListener('keypress', function(e) {

console.log(e.target);
});


.root {
padding-right: 1px;
}

#parent>div {
border-color: yellow;
float: left;
}



Qué

es

Lorem

Ipsum

</div>



the problem is complicated because I am using for each word a div.



I need to use div so you can display the suggestions in the words (I'm doing a spellchecker)



enter image description here





So you need to do a list of suggestions based on the word the user has typed. To do that better use keyup event to get the word after being typed and not before.
– facundo
Jun 30 at 3:50





3 Answers
3



You could use window.getSelection() to get the actual node under the cursor:


window.getSelection()




document.getElementById('parent').addEventListener('keydown', event => {
const actualTarget = window.getSelection().anchorNode.parentNode;
console.log(actualTarget);
});


.root {
padding-right: 1px;
}

#parent>div {
border-color: yellow;
float: left;
}



Qué

es

Lorem

Ipsum

</div>



Try this approach. I suggest you to use keyup event to get the final word after typed to generate your list of suggestions:




document.querySelectorAll('.root').forEach(function(el) {
// Do stuff here
el.onkeyup = function(e){
console.log(e.target);
};

});


.root {
padding-right: 1px;
}

#parent>div {
border-color: yellow;
float: left;
}



Qué

es

Lorem

Ipsum

</div>



Use span instead of div, and it is not a good practice to use float: left; here.


span


div


float: left;





This does not answer the question. Using spans instead has the same problem.
– CertainPerformance
Jun 30 at 3:21



span





@CertainPerformance i edited my question added more information over my use the div
– x-rw
Jun 30 at 3:28





@x-rw Ok, but I don't know the answer, I was only commenting that this answer doesn't achieve anything
– CertainPerformance
Jun 30 at 3:31






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Comments

Popular posts from this blog

paramiko-expect timeout is happening after executing the command

how to run turtle graphics in Colaboratory

Export result set on Dbeaver to CSV