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
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:
const para locales que no deben reasignarse.throw new Error cuando esas suposiciones se invaliden. Esto ayuda mucho a la depuración en JavaScript ( "fail fast" ).{ } ) que refleja la estructura del DOM. 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" ) ) ); }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);