Estoy haciendo un proyecto de máquina de cotizaciones aleatorias usando javaScript de vainilla. Estoy haciendo este proyecto usando fetch-api(quotable.io) y manipulación simple de Dom. Mi código es correcto, pero hay algunos problemas que no puedo identificar.
Mi código es:
<html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="Random.css"> <title>Random Quotes Machines</title> </head> <body> <h1>Random Quotes </h1> <br> <br> <div class="container"> <p class="p">undefined </p> <h6 class="author"> undefined</h6> </div> <button class="NextQuote" onclick="NextQuote()">NextQuote</button> <!-- <button class="previous">Previous</button> --> <script> let container = document.getElementsByClassName("container"); let p = document.querySelector(".p"); let author = document.querySelector(".author"); let rem; function NextQuote (){ rem = Math.floor(Math.random()*100); fetch('https://api.quotable.io/random') .then(response => response.json()) .then(quotes => { p.innerHtml = '"${quotes.content}"'; } ); } </script> </body> </html>
Debe cambiar innerHtml
a innerHTML
.
Y necesita cambiar '"${quotes.content}"'
a quotes.content
.
El resultado sería:
fetch('https://api.quotable.io/random') .then(response => response.json()) .then(quotes => { p.innerHTML = quotes.content; } );
Su muestra casi funciona. Solo hay algunos pequeños problemas en su código:
quotes.content
contiene un texto sin formato, para agregar el texto al párrafo, puede usar p.textContent
en su lugar.quotes.content
no se interpolará. Para que funcione, reemplace la línea p.innerHtml = '"${quotes.content}"';
with p.textContent = `"${quotes.content}"`;