0
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="stylesheet" href="write.css">
  <script src="https://code.jquery.com/jquery-3.7.0.min.js"></script>
  <script defer src="test.js"></script>
  <title>Document</title>
</head>

<body>
  <div id="edit" contenteditable="true"></div>
  <input type="file" class="img-upload">
</body>

</html>
const edit = document.querySelector("#edit");
const pTage = document.createElement("p");
pTage.innerHTML = "<br>";

edit.appendChild(pTage);
edit.addEventListener("keydown", () => {
  let nodes = edit.firstChild;
  if (nodes === null || nodes.nodeName !== "P") {
    const edit = document.querySelector("#edit");
    const pTage = document.createElement("p");
    pTage.innerHTML = "<br>";
    edit.appendChild(pTage);
  }
});

let a = document.querySelector(".img-upload");
a.addEventListener("change", (e) => {
  let reader = new FileReader();
  reader.onload = (e) => {
    const imgWrap = document.createElement("span");
    const img = document.createElement("img");
    img.setAttribute("src", e.target.result);
    imgWrap.appendChild(img);

    const dd = document.querySelector("#edit").appendChild(imgWrap);
  };
  reader.readAsDataURL(e.target.files[0]);
});

When you navigate to the writing page, you find that there is already a p tag created, and you want to write text only within this p tag. Additionally, you wish to attach an image. The problem is that when you attach an image, the cursor is positioned next to the image, and if you start typing after a line break, the text is placed inside a span tag instead of the p tag.

How can I attach an image, create a line break, and then have the ability to write text inside a newly generated p tag?

0 Answers0