En mi programa, enumera tres elementos en una lista ordenada que tiene identificadores. Luego, cuando hace clic en un botón, se le solicita que ingrese el número correspondiente al elemento numerado en la lista que desea reemplazar. Luego, otro mensaje le pregunta con qué desea reemplazar el texto en la pantalla. Tengo declaraciones if configuradas para verificar qué número se ingresa y uso .replaceChild para reemplazar el texto en la lista con el texto ingresado en el indicador. Supuse que esto funcionaría de manera similar a cómo lo hace el uso de .innerHTML para reemplazar texto, pero no funciona para mí. Cualquier ayuda sería apreciada.
Aquí está mi código.
function replaceItem() { var listNum = prompt("Which item are you replaceing 1, 2 or 3?"); var newItem = prompt("What is the name of the new item?"); if (listNum === 1) { var item_one = document.getElementbyId("item1"); item_one.replaceChild(newItem, item_one); } if (listNum === 2) { var item_two = document.getElementbyId("item2"); item_two.replaceChild(newItem, item_two); } if (listNum === 3) { var item_three = document.getElementbyId("item3"); item_three.replaceChild(newItem, item_three); } }HTML.
<!DOCTYPE HTML> <html> <head> <meta charset="UTF-8"> <title>Island Scenario</title> </head> <body> <h3>You are being sent to an island by yourself to survive for 1 week.</h3> <br> <h3>You are allowed to bring the clothes on your back but are also being given three items.</h3> <br> <h3>Out of the three items that you are initially given, you are allowed to switch out one of the items for something of your choice.</h3> <br> <h4>Here are your current items.</h4> <ul> <li id="item1">Water Bottle</li> <li id="item2">Lighter</li> <li id="item3">Backpack</li> </ul> <p>Click the button to replace an item.</p> <button onclick="replaceItem();">Click Me</button> </body> </html>Además del error tipográfico en su intento, esta no es la forma de usar replaceChild. Con replaceChild, debe especificar qué elemento de nodo HTML reemplazar, junto con el nuevo elemento con el que reemplazar. Aquí hay una manera más fácil. Simplemente use el índice natural de los elementos y el innerText para reemplazar el que desee. Le di a UL un className para hacer de este un mejor ejemplo.
En esta línea, document.querySelectorAll('.theList li') crea una lista HTMLElement iterable y [listNum - 1] toma la entrada, resta uno para obtener el elemento LI correcto.
document.querySelectorAll('.theList li')[listNum - 1].innerText = newItem; function replaceItem() { var listNum = prompt("Which item are you replaceing 1, 2 or 3?"); var newItem = prompt("What is the name of the new item?"); document.querySelectorAll('.theList li')[listNum - 1].innerText = newItem; return } <h3>You are being sent to an island by yourself to survive for 1 week.</h3> <br> <h3>You are allowed to bring the clothes on your back but are also being given three items.</h3> <br> <h3>Out of the three items that you are initially given, you are allowed to switch out one of the items for something of your choice.</h3> <br> <h4>Here are your current items.</h4> <ul class='theList'> <li id="item1">Water Bottle</li> <li id="item2">Lighter</li> <li id="item3">Backpack</li> </ul> <p>Click the button to replace an item.</p> <button onclick="replaceItem();">Click Me</button>replaceChild no es la mejor manera de manejar este escenario, ya que reemplazar el texto interno o el contenido de texto del nodo sería más sencillo, pero si quiere saber por qué no funciona, es porque replaceChild quiere dos nodos HTML como parámetros, newNode y oldNode , dado que tiene nodos de texto dentro de los elementos li , debe obtenerlos con la propiedad childNodes , lo mismo ocurre con el newNode , necesita crear un textNode con document.createTextNode .
Aparte de esto, le sugiero que haga una función para manejar esa lógica para seguir los principios DRY , ya que está repitiendo el código y lo único que cambia es el selector del padre:
function replaceItem() { const listNum = prompt("Which item are you replaceing 1, 2 or 3?"); const newItem = document.createTextNode(prompt("What is the name of the new item?")) replace(listNum, newItem) } function replace(n, newNode) { const parent = document.getElementById(`item${n}`); const oldNode = parent.childNodes[0] parent.replaceChild(newNode, oldNode); } <body> <h3>You are being sent to an island by yourself to survive for 1 week.</h3> <br> <h3>You are allowed to bring the clothes on your back but are also being given three items.</h3> <br> <h3>Out of the three items that you are initially given, you are allowed to switch out one of the items for something of your choice.</h3> <br> <h4>Here are your current items.</h4> <ul> <li id="item1"> Water Bottle </li> <li id="item2"> Lighter </li> <li id="item3"> Backpack </li> </ul> <p>Click the button to replace an item.</p> <button onclick="replaceItem();">Click Me</button>