I want to replace all the words with span, my code is as follows:
let written = '';
document.getElementById('test').addEventListener('keyup', function(e) {
var palabra = written;
written += String.fromCharCode(e.which);
if (e.which === 32) {
let text = document.getElementById('test').innerHTML;
console.log(text);
var wordsWithSpan = text.split(' ').map(function(c) {
return '<span class="word">' + c + '</span>';
}).join('');
document.getElementById('test').innerHTML = wordsWithSpan;
}
});
.word {
color: red;
padding-right: 2px;
}
div {
margin: 50px;
}
<div contenteditable="true" id="test">hola mundo tierra</div>
At the moment it only works with the first attempt ( press space bar ), from the second attempt I get the text but with plainspan
text labels .
What I need is to get on nodes not on text.
The problem is that every time you insert a character, you have to check for the presence of spans and remove them, to simply manipulate the text. I leave you an example:
To get the text use
textContent
... What I do is capture the text that is displayed inside thediv
, and then separate it by spaces using a regular expression/[\b\s\n]+/gi
, then I assign the content of thediv
, but this time converted to words withspan
.The problem with assigning the content again is that the position of the cursor is lost... For this you can make a function that changes the cursor.
To add spaces at the end of the word I do
<a> </a>
. Although I could have just added a space usinginnerHTML
, I recommend usingappendChild
... For the same reason that the cursor returns to the beginning, because I am usinginnerHTML
, and also, determining the position when there are several<span>
mixed in the HTML structure is a complicated task.