Clean content whose tag is the same

2

I have several span tags with the same class and I am treated by a function that traverses all span and clean its content.

I have raised this but it does not work for me

function limpiarError(){
    var spanTag = document.getElementsByTagName("span");

    for (var i=0; i < spanTag.length; i++){
        spanTag.elements[i].innerHTML = "";
    }
}
<span id="errorId">1</span>
<span id="errorNom">2</span>
<span id="errorFecha">3</span>
<span id="errorTelf">4</span>
    
asked by Eduardo 01.12.2017 в 18:36
source

2 answers

5

getElementsByTagName() returns an array, not an object that has a property elements . You also have to execute the function that you do not do. In this example, it is executed when the page loads:

function limpiarError(){
    var spanTag = document.getElementsByTagName("span");

    for (var i=0; i < spanTag.length; i++){
        spanTag[i].innerHTML = "";
    }
}


window.onload = limpiarError();
<span id="errorId">1</span>
<span id="errorNom">2</span>
<span id="errorFecha">3</span>
<span id="errorTelf">4</span>
    
answered by 01.12.2017 в 18:44
3

With jquery

function limpiar() {
    $("span.test").html("");
}

setTimeout(limpiar, 1000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="test"> 123 </span>
<span class="test"> 123 </span>
<span class="test"> 123 </span>
    
answered by 01.12.2017 в 18:44