Quisiera saber la diferencia entre dos métodos o funcionalidades de jQuery que pueden llegar a confusión en mi caso, incluso leyendo la API de ambas utilidades como pueden ser:
- .text()
- .html()
Según w3s, .text() coloca y retoca un valor en un atributo o etiqueta de nuestro HTML; y html() coloca y retorna un valor en un atributo o etiqueta con la posible diferencia de añadir código html.
Ejemplo .text():
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("p").text("Hello world!");
});
});
</script>
</head>
<body>
<button>Set text content for all p elements</button>
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
</body>
</html>
Ejemplo .html():
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("p").html("Hello <b>world!</b>");
});
});
</script>
</head>
<body>
<button>Change content of all p elements</button>
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
</body>
</html>
¿A qué se debe la diferencia realmente? ¿Se pueden usar los dos indistintamente?