0

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.

Michael Moreno
  • 947
  • 1
  • 7
  • 24

2 Answers2

0

You can refer to this question.

Change the third line to element.innerHTML += wrapped;

0

To append something in JavaScript you need to use plus sign that is for concatenating the strings or variables.

<script>
const element = document.querySelector('td'); 
const wrapped = `<p class="x">${element.innerHTML}</p>`;
element.innerHTML += wrapped;
</script>
John Doe
  • 1,401
  • 1
  • 3
  • 14
  • I don't just need to append data, I need to wrap the current data in an element. Using your method results in my current line being unaltered while a duplicate of it is created next to it that is correctly formatted. – Michael Moreno Feb 10 '21 at 23:18
  • You should add some more code to understand us what exactly you want to do. – John Doe Feb 11 '21 at 03:07