How can I get the id in classes with equal names?

4

How can I get the id of the alternative and know if it is 0, 1 or 2.

<div class="quest-alternatives">
<p class="brand-alternative">
<span class="brand-id hidden" style="display: none;">123</span>
<span class="radio-button" id="brand-0"></span>
<label for="brand-0" class="brand-name">Opção 0</label></p>

<p class="brand-alternative">
<span class="brand-id hidden" style="display: none;">456</span>
<span class="radio-button" id="brand-1"></span>
<label for="brand-1" class="brand-name">Opção 1</label></p>

<p class="brand-alternative">
<span class="brand-id hidden" style="display: none;">789</span>
<span class="radio-button" id="brand-2"></span>
<label for="brand-2" class="brand-name">Opção 2</label></p></div>

I used $('span.brand-id.hidden').html() but it only returned me the id of the first alternative I also tried to use $.each but I do not quite understand how it works.

    
asked by anonymous 06.04.2014 / 23:32

2 answers

1

When you have a selector that returns more than one element, and you call the html method on it, it only returns the result of the first element. Several jQuery functions work the same way.

If you want the contents of all the elements (in a list, for example), you can use the .map function. :

$('span.brand-id.hidden').map(function() {
    return $(this).html();
});

Example in jsFiddle . The result is an array-like that you can save or use in a for normal (i.e. using length , accessing elements as lista[0] etc).

    
06.04.2014 / 23:47
1

Try to make a function to check a property of the element itself (removing unnecessary html code), something like (I removed span hidden with value in html and set a value to name ):

<div class="quest-alternatives">
<p class="brand-alternative">

<span class="radio-button brand-id" name="123" id="brand-0"></span>
<label for="brand-0" class="brand-name">Opção 0</label></p>

<p class="brand-alternative">

<span class="radio-button brand-id" name="456" id="brand-1"></span>
<label for="brand-1" class="brand-name">Opção 1</label></p>

<p class="brand-alternative">

<span class="radio-button brand-id" name="789" id="brand-2"></span>
<label for="brand-2" class="brand-name">Opção 2</label></p></div>

JQuery should be this:

$('.brand-id').each(function(index, value){
 var id = $(this).attr("id"); // retorna brand-0/brand-1/brand-2
 var valor = $(this).attr("name"); // retorna 123/456/789
 alert(id + "-" + valor);
});

Here's the JSFiddle with the code.

    
06.04.2014 / 23:44