Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

184
Vistas
Javascript adding li element value to the empty list if it is not existing

I have a problem in Javascript.I am adding new list items to the 'ul' elements and this list is empty at first and I do not want to add same values twice. When I write the if statement I get the exception because my list is empty so the result return null. How can I fix this this problem? Thank you in advance...

Html Codes

 <input type="text" id="the-filter" placeholder="Search For..." />
        <div class="list-container">
            <ul id="myList"></ul>
            <button  id="button">Click</button>

Javascript Codes

let newlist = document.querySelector("#myList");
const li = document.getElementsByClassName('list-group-item');
const button = document.getElementById("button");
const button.addEventListener('click' , listName);
const input = document.getElementById("the-filter");

function listName()

    const inputVal = input.value;
 
    for (i = 0; i < li.length; i++) {
   
        if ((li[i].innerHTML.toLocaleLowerCase().includes(inputVal) && inputVal!="") || 
        (li[i].innerHTML.toUpperCase().includes(inputVal) && inputVal!="")) {             
            let newItem = document.createElement("li");
            li[i].classList.add("list-group-item");
            let textnode = document.createTextNode(li[i].innerHTML.toLocaleLowerCase());
            newItem.appendChild(textnode);

           if((newlist.children[0].innerHTML.toLocaleLowerCase().includes(inputVal))){
            newlist.insertBefore(newItem, newlist.childNodes[0]);    
           }

          }
        }
}
about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

If I understood the task correct, you need to add items to the list by button click.
If same item exists (case insensitive), then nothing happens.

const list = document.querySelector("#myList");
const button = document.getElementById("button");
button.addEventListener("click", listName);
const input = document.getElementById("the-filter");

function listName() {
  const inputVal = input.value;
  const [...lis] = document.getElementsByClassName("list-group-item");
  
  const same = lis.find((el) => el.textContent.toLowerCase() === inputVal.toLowerCase());
  if (same) {
    return;
  }
  
  let newItem = document.createElement("li");
  newItem.classList.add("list-group-item");
  newItem.textContent = inputVal;
  list.appendChild(newItem)
}
<input type="text" id="the-filter" placeholder="Search For..." />
<div class="list-container">
  <ul id="myList"></ul>
  <button id="button">Click</button>
</div>

about 4 years ago · Juan Pablo Isaza Denunciar

0

You're on the right track with event listeners and element creation, but your original code didn't quite seem to match your stated goal.

Here's a solution you might find useful, with some explanatory comments:

  // Identifies some DOM elements
  const
    input = document.getElementById("my-input"),
    newList = document.getElementById("my-list"),
    items = document.getElementsByClassName('list-group-item'),
    button = document.getElementById("my-button");
  
  // Focuses input, and calls addItem on button-click
  input.focus();
  button.addEventListener('click', addItem);

  // Defines the listener function
  function addItem(){

    // Trims whitespace and sets string to lowerCase
    const inputTrimmedLower = input.value.trim().toLocaleLowerCase();
    
    // Clears and refocuses input
    input.value = "";
    input.focus();

    // Ignores empty input
    if (!inputTrimmedLower) { return; }
    
    // Ignores value if a list item matches it
    for (const li of items) {
      const liTrimmedLower = li.textContent.trim().toLocaleLowerCase();
      if (liTrimmedLower === inputTrimmedLower) {
        console.log(`${inputTrimmedLower} is already listed`);
        return;
      }
    }

    // If we got this far, we want to add the new item
    let newItem = document.createElement("li");
    newItem.classList.add("list-group-item");
    newItem.append(inputTrimmedLower); // Keeps lowerCase, as your original code
    newList.prepend(newItem); // More modern method than `insertBefore()`
  }
<input id="my-input" />
<ul id="my-list"></ul>
<button id="my-button">Click</button>

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda