jQuery function to select values in divs and play to an array

1

I'm getting the values of several <div> s with the same class name and trying to play to an array in jQuery, but as I'm starting in the language I'm not getting it, I already searched the internet and nothing I found gave me a solution .

As an example:

var array = [];
var count = $('.card-header').length;
var name = $('.card-header').text();
var i, proximo;
for (i = 0; i < count; i++) {
  proximo = array.length;
  array[proximo] = name;
}

$('.rodapeCat').text(array);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script><spanclass="card-header">Casa</span><br>
<span class="card-header">Porta</span><br>
<span class="card-header">Janela</span><br>
<span class="card-header">Escada dos fundos</span><br>
<hr/>

<!--DIV apenas para mostrar se os valores Casa, Porta, Janela, Escada dos fundos estão na array-->
<div class="rodapeCat"><div>

I wanted the array to look like this: ['Casa', 'Porta', 'Janela', 'Escada dos fundos'] .

Would anyone have any light for my problem?

    
asked by anonymous 23.07.2018 / 04:04

1 answer

1

Try this:

var array = [];
$('.card-header').each(function(i) {
  array.push($(this).html());
});

$('.rodapeCat').html(JSON.stringify(array));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script><spanclass="card-header">Casa</span><br>
<span class="card-header">Porta</span><br>
<span class="card-header">Janela</span><br>
<span class="card-header">Escada dos fundos</span><br>
<hr/>

<!--DIV apenas para mostrar se os valores Casa, Porta, Janela, Escada dos fundos estão na array-->
<div class="rodapeCat"><div>

Use method each(function) to iterate the elements of a jQuery selector.

One of the ways to convert an array to string is JSON.stringify .

To get the contents of a <div> or set this content, use html() and html(conteudo) .

To add items to an array without having to worry about its size, use method push(elemento) .

    
23.07.2018 / 04:12