Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

92
Views
cómo crear un <a></a> dentro de <li></li> todos están dentro de <ul></ul> con JS

Tengo esta ul que está hecha por HTML y quiero crear elementos dentro con JS

Código HTML:

 <ul id="navbar__list"> </ul>

y código JS:

 var ul = document.getElementById("navbar__list"); var link1 = document.createElement("a"); var Li1 = document.createElement("li").appendChild(document.createElement("a")); var sec1 = ul.appendChild(Li1) link1.innerHTML = "Section 1" link1.href ="#section1"

todo lo que obtuve fue sin texto y como principiante, no sé qué está mal

about 4 years ago · Santiago Gelvez
2 answers
Answer question

0

Debe pasar link1 a su llamada appendChild . En este momento, su código llama a createElement("a") dos veces y pasa el segundo <a> no inicializado a appendChild , que no es lo que desea.

Querrás esto:

  • Use const para locales que no deben reasignarse.
  • Esté a la defensiva: debido a que JavaScript no ofrece seguridad de tipo en tiempo de compilación u otras garantías, es una buena idea verificar siempre sus suposiciones y throw new Error cuando esas suposiciones se invaliden. Esto ayuda mucho a la depuración en JavaScript ( "fail fast" ).
  • Cuando construyo árboles de elementos DOM en JS, encuentro útil colocar cada elemento en su propio ámbito anónimo ( { } ) que refleja la estructura del DOM.
    • Esto también ayuda a prevenir errores en los que los elementos no se relacionan correctamente.
 const ul = document.getElementById("navbar__list"); if( !ul ) throw new Error( "Couldn't find navbar__list" ); { const li = document.createElement("li"); ul.appendChild( li ); { const aLink = document.createElement("a"); aLink.textContent = "Section 1"; aLink.href = "#section1"; li.appendChild( aLink ); } }

Sorprendentemente, la API DOM es un poco detallada: no hay una forma sucinta de crear elementos con sus atributos y conjunto de contenido interno, en su lugar, necesitamos llamadas explícitas a createElement y appendChild . Se han propuesto algunas alternativas que usan técnicas de tiempo de compilación, como JSX , como una alternativa más liviana, podría usar una función de ayuda como esta:

 /** @param {string} tagName @param {[string, string][]} attributes - Array of 2-tuples @param {HTMLElement | HTMLElement[] | string} content - Either: one-or-many HTML elements, or string textContent */ function create( tagName, attributes, content ) { const e = document.createElement( tagName ); for( let i = 0; i < attributes.length; i++ ) { const pair = attributes[i]; e.setAttribute( pair[0], pair[1] ); } if( typeof content === 'string' ) { e.textContent = content; } else if( Array.isArray( content ) ) { for( const child of content ) { e.appendChild( child ); } } else if( typeof content === 'object' && content !== null ) { e.appendChild( content ); } return e; }

Usado así:

 const ul = document.getElementById("navbar__list"); if( !ul ) throw new Error( "Couldn't find navbar__list" ); { ul.appendChild( create( "li", [], create( "a", [ [ "href", "#section1" ] ], "Section 1" ) ) ); }
about 4 years ago · Santiago Gelvez Report

0

Utilizar este:

 var ul = document.getElementById("navbar__list"); var li = document.createElement("li"); ul.appendChild(li); var link = document.createElement("a"); link.setAttribute('href', '#section1'); link.innerHTML = "Section 1"; li.appendChild(link);
about 4 years ago · Santiago Gelvez Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!