I am currently learning the basics of JAVASCRIPT
, for now I am in html
and dom
, specifically in Crear, modificar y eliminar nodos
, I have the following html
basic to test the different functionalities:
var p = document.createElement("p");
document.body.appendChild(p);
var texto = document.createTextNode("Texto que se agregó por javascript");
p.appendChild(texto);
//encontrar el primer elemento de tipo p
var primer_p = document.getElementsByTagName("p")[0];
document.body.removeChild(primer_p); //Remueve el elemento p del documento html
<!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">
<title>Ejemplos</title>
</head>
<body>
<p>Este elemento p será eliminado de la hoja html</p>
<script type="text/javascript" src="dom.js"></script>
</body>
</html>
Before putting the following line, which is the one that follows the tutorial that I am following:
document.body.removeChild(primer_p);
Without looking at the tutorial, I first looked at the different methods that the variable had primer_p
, I found the method remove()
, just like that, and it also removes the element.
primer_p.remove();
- Do both methods do the same thing?
- If not, what is the main difference between the two?
Difference in the way of referencing the object. Although you did , it
document.body.removeChild(primer_p);
works because the paragraph is a body node. But what happens if we add a<span>
y inside the paragraph? It will mark an error because the paragraph is no longer a direct node ofbody
, but rather it isspan
in the middle.Now the method
remove()
removes the item, no matter what level it's at, it's a direct reference.