I'm trying to using pure JS (not jquery) to add a <del>
insides the <div>
that wraps the text 'abc'
For practice purpose, i'm not allowed to innerHTML method, inline CSS, or jquery etc. plain js.
<html>
<div class='todo'>abc</div>
</html>
my attempt.
const todo = document.querySelector('.todo')
const del = document.createElement('del')
todo.appendChild(del)
But this ended up with
<div class='todo'>abc <del></del></div>
.
I'd like to have
<div class='todo'><del>abc</del></div>
.
CodePudding user response:
You can do a short trick to achieve this:
1) Add textContent
of todo
to del
's textContent
.
del.textContent = todo.textContent;
2) Remove the textContent
of todo
.
todo.textContent = "";
3) Append del
as a child.
todo.appendChild(del)
const todo = document.querySelector('.todo')
const del = document.createElement('del')
del.textContent = todo.textContent;
todo.textContent = "";
todo.appendChild(del)
<div class='todo'>abc</div>
CodePudding user response:
You can use the innerText method
const todo = document.querySelector('.todo')
const del = document.createElement('del')
del.innerText = todo.innerText
todo.innerText = ""
todo.appendChild(del)
CodePudding user response:
Move the content - saves blanking it
const todo = document.querySelector('.todo')
const del = document.createElement('del')
del.append(todo.firstChild)
todo.appendChild(del)
<div class='todo'>abc</div>
Or simpler
const todo = document.querySelector('.todo')
todo.innerHTML = todo.textContent.strike()
<div class='todo'>abc</div>