Yacomini Yacomini - 1 year ago 87
HTML Question

Using getElementsByTagName then using getElementById

I'm trying to get the value from an input with an ID inside a LI element.

But when I call the

I get the error
numLi[i].getElementById is not a function
being numLi an array with LI elements. Here's my whole js code

var headOne = document.getElementById('inputHead').value;
var archive = document.getElementById('inputPara').value;
var numLi = document.getElementById('uList').getElementsByTagName('li');
var tagsToPost = '';
for(i = 0;i<numLi.length;i++)
var ff = numLi[i].getElementById('tagOne');

tagsToPost = tagsToPost + ff.value + ',';
tagsToPost = tagsToPost + ff.value;


And the html part I'm trying to access

<form action="javascript:void(0);">
<div class="col-md-3">

<div id="enlacesList">
<ul id="uList">

<li class='listaLink'><input type="text" id="tagOne" class="tags" placeholder="Tags" autocomplete="off"></li>
<li class='listaLink'><input type="text" id="tagOne" class="tags" placeholder="Tags" autocomplete="off"></li>

<button id="addgregador" type="button" autocomplete="off"><span class="glyphicon glyphicon-plus"></span></button><button id="desadd" type="button" autocomplete="off"><span class="glyphicon glyphicon-minus"></span></button>
<div class="col-md-9" id="containerTexto">
<div id="textoPregunta">
<div id="textHeading"><input type="text" name="headingOne" id="inputHead" placeholder="Titulo de la pregunta" autocomplete="off"></div>
<div id="textContent"><textarea id="inputPara" rows="33" cols="84" placeholder="Respuesta, explicación..." autocomplete="off"></textarea></div>
<input type="submit" id="editOk" value="Enviar" class="btn btn-primary" autocomplete="off"><input type="reset" id="editNot" value="Cancelar" class="btn btn-danger" autocomplete="off">

The program breaks in the line
var ff = numLi[i].getElementById('tagOne');

Answer Source

The getElementById function is defined only on document, not on DOM nodes in general. See its MDN article. This is because ids should be unique at document level, so it doesn't make sense to scope it to an individual element.

So first of all, don't use the same id for multiple elements in one document. If you have only one input per LI element, remove the id attribute and get them for example like this.

var ff = numLi[i].children[0];