jQuery function for selecting values in Divs and playing for an array

Asked

Viewed 33 times

1

I’m taking the values of several <div>s with the same class name and trying to play for an array in jQuery, but as I’m starting in the language I’m not getting, I’ve 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>
<span class="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'].

Someone would have some light for my problem?

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>
<span class="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 the method each(function) to iterate the elements of a jQuery selector.

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

To take the contents of a <div> or else define this content, use the methods html() and html(conteudo).

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

Browser other questions tagged

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