André Martins André Martins - 4 months ago 8
jQuery Question

.text() not returning value

I'm using this code to create a

<ul><li>
of the classes attached to the div
.lista-produtos
.

$(document).ready(function(){

var alts = {};
$('.lista-produtos').each(function(){
var classes2 = $(this).attr('class').split(' ');
for (var i = 0; i < classes2.length; i++) {
var matches2 = /^tipo\-(.+)/.exec(classes2[i]);
if (matches2 != null) {
var produto = matches2[1];
}
}
if(!alts[classes2]){
alts[classes2] = true;
$('ul.filters').append('<li class="filter-produto">'+ produto +'</li>');
}
});
});


The code above generates
<li>
s inside of the
<ul class="filters">
. So the code is something like this:

<ul class="filters">
<li class="filter-produto active">Produto 1<li>
<li class="filter-produto">Produto 2<li>
<li class="filter-produto">Produto 3<li>
<li class="filter-produto">Produto 4<li>
</ul>


As you can see, one of the
<li>
s will have an additional class named "active", and the problem is I need to get the text inside of it (Produto 1) to use on another code but it's not working:

var produto2 = $('li.filter-produto.active').text();


I tested
alert(produto2);
to see if the code worked but it only returns a blank value and not the text inside the
<li>
.

dee dee
Answer

Sadly I don't have rep to comment, but can you show us the order of the stuff happening?

Perhaps you are asking for the value before the active class it attached to the li. Something like this:

// Function to create the ul and lis

var produto2 = $('li.filter-produto.active').text();

// Function that adds the active class

So maybe the li.filter-produto.active doesn't exist when you ask for it's value?

Comments