Skip to content

Instantly share code, notes, and snippets.

@huannvictor
Created July 1, 2022 21:27
Show Gist options
  • Save huannvictor/9bb43823e514ae8be690f4b06699929f to your computer and use it in GitHub Desktop.
Save huannvictor/9bb43823e514ae8be690f4b06699929f to your computer and use it in GitHub Desktop.
manipulando o DOM
//* adicionar novo item
function newPhone() {
//* 1. seleciona o elemento que irá receber os novos filhos
const phoneGroup = document.querySelector("form#phones");
//* 2. cria os filhos
const newPhoneField = document.createElement("p");
const newPhoneLabel = document.createElement("label");
const newPhoneInput = document.createElement("input");
newPhoneInput.setAttribute("name", "phone");
newPhoneLabel.innerText = `Telefone ${phoneGroup.length + 1}: `;
//* 3. instancia no HTML
phoneGroup.appendChild(newPhoneField);
newPhoneField.appendChild(newPhoneLabel);
newPhoneField.appendChild(newPhoneInput);
}
//* imprimir os itens
function printPhones() {
//* 1. seleciona o elemento que irá receber a lista dos elementos
const showList = document.getElementById("list");
//* 2. zera a lista para não criar várias listas repetidas
showList.innerHTML = "";
//* 3. cria o elemento que encapsula a lista
const phoneList = document.createElement("p");
//* 4. cria uma lista com os valores dos inputs
const phones = document.querySelectorAll("input[name='phone']");
//* 5. instancia cada item dentro da lista
phones.forEach((phone, index) => {
phoneList.innerHTML += `Telefone: ${index + 1}: ${phone.value}<br />`;
});
//* 6. instancia a lista no HTML
showList.appendChild(phoneList);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment