Remove empty spaces in JS arrays

Asked

Viewed 852 times

-1

I would like to know how to eliminate the gaps that are in a vector.

The situation is as follows: I need to read all the text tags of an HTML page and store them in an array so that I can work them individually in the future. I created an array that has the registered tags, another to store the tags that are found on the page according to the ones that are registered in the first array. However, white spaces are also saved with each iteration.

var tags = ["h1", "h2", "h3", "h4", "h5", "h6", "h7", "p", "a", "li", "span", "strong", "li"];
        var elementosPag = [];

        var nroElementos = document.body.getElementsByTagName("*").length;  

        for(var i = 0; i<tags.length; i++)
            elementosPag.push(document.body.getElementsByTagName(tags[i]));
  • What do you mean "blank space" ? Your question is not clear! Yes <p> </p> has a blank space! That would be it ?

  • Because you need to read all HTML tags if with javascript you have direct access to the DOM of the page. Why create overload in the browser?

  • @wmsouza GAPS = EMPTY SPACES

1 answer

-1

So far I have been able to solve this way, but I do not know if it is the most optimized solution:

        var tags = ["h1", "h2", "h3", "h4", "h5", "h6", "h7", "p", "a", "li", "span", "strong", "li"];
        var elementosPag = [];
        var matches = [];
        var nroElementos = document.body.getElementsByTagName("*").length;  

        for(var i = 0; i<tags.length; i++){
            elementosPag.push(document.body.getElementsByTagName(tags[i]));
            if(elementosPag[i].length != 0)
                matches.push(elementosPag[i]);
        }
        for(var i = 0; i<matches.length; i++){
            console.log(matches[i])

        }

Browser other questions tagged

You are not signed in. Login or sign up in order to post.