Answer the question
In order to leave comments, you need to log in
How to remove all text nodes inside parent tag?
Hello! I'm trying to remove all text nodes from an element.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link href="https://fonts.googleapis.com/css?family=Roboto&display=swap" rel="stylesheet">
<link rel="stylesheet" href="general.css">
<title>Document</title>
</head>
<body>
<div class="wrp">
<div class="container">
<h1>Hello</h1>
<input type="text">
<input type="text">
<label for=""><input type="checkbox" onclick="window.event.returnValue=false">Caps Lock</label>
<button>Hello!</button>
<div><p>WRLD!</p><p>HI</p></div>
</div>
</div>
<script src="main.js"></script>
</body>
</html>
"use strict"
let elem = document.querySelector(".container");
console.log(elem);
function deleteTextNode(parent){
for( let i = 0; i < parent.children.length; i++){
if (parent.children[i].firstElementChild){
deleteTextNode(parent.children[i]);
}else{
parent.children[i].textContent = "";
}
console.log(parent.children[i]);
}
}
deleteTextNode(elem);
Answer the question
In order to leave comments, you need to log in
Well, you just delete the text inside the elements, the elements themselves remain
I tried to do it in another way (if anyone is interested)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link href="https://fonts.googleapis.com/css?family=Roboto&display=swap" rel="stylesheet">
<link rel="stylesheet" href="general.css">
<title>Document</title>
</head>
<body>
<div class="wrp">
<div class="container">
<h1>Hello</h1>
<input type="text">
<input type="text">
<label for=""><input type="checkbox" onclick="window.event.returnValue=false">Caps Lock</label>
<button>Hello!</button>
<div><p>WRLD!</p><p>HI</p></div>
</div>
</div>
<script src="main.js"></script>
</body>
</html>
"use strict"
let elem = document.querySelector(".container");
console.log(elem);
function remove(parent){
let child = parent.childNodes;
for(let i = 0; i < child.length; i++){
if(child[i].nodeType == 3){
parent.removeChild(child[i]);
i--;
}else{
remove(child[i]);
}
}
}
remove(elem);
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question