I'm building a notetaking app. I have a <td contenteditable="true">
serving as an input where you type text. I want to apply CSS styles to specific lines of text upon pressing enter, presumably by wrapping html elements around the desired text and targeting their classes in CSS. I need to be able to do this multiple times to multiple lines in a single input box.
I've tried the following
const element = document.querySelector('td');
const wrapped = `<p class="x">${element.innerHTML}</p>`;
element.innerHTML = wrapped;
But this only works once, doing it twice results in the first wrap being wrapped by the second, i.e <p><p>${text}</p></p>
. I need the elements to be adjacent rather than nested since each line will have it's own custom styling, like <p>${text1}</p><p>{text2}</p>
I've also tried appending the element rather than setting it as the innerHTML, and this almost works, but it ends up with my cursor being placed at the beginning of the input every time, which isn't acceptable because the user is needs to able to continuously type new lines.