30

I have 3 Columns of ULs each a Dynamic UL container that can have anywhere from 0-9 LI containers (eventually more). All my LI elements have an attribute "rel" which I am trying to ultimately find that attribute and use it for something else on all LI elements within that parent DIV. I do eventually want to find more based on each but for not the very least the rel.. Any Ideas how I can achieve that with jQuery? Example:

<ul id="column1">
   <li rel="1">Info</li>
   <li rel="2">Info</li>
   <li rel="3">Info</li>
</ul>
<ul id="column2">
   <li rel="4">Info</li>
   <li rel="5">Info</li>
   <li rel="6">Info</li>
</ul>
<ul id="column3">
   <li rel="7">Info</li>
   <li rel="8">Info</li>
   <li rel="9">Info</li>
</ul>

these elements are all sortable as well. So when I get a list of them I want to also keep them in the order they were found from top to bottom of each column.

I have tried find(), parent(), and similar, maybe I am approaching it wrong. But its still worth mentioning to help come up with an idea

chris
  • 36,115
  • 52
  • 143
  • 252

4 Answers4

57

Are you thinking about something like this?

$('ul li').each(function(i)
{
   $(this).attr('rel'); // This is your rel value
});
pixelfreak
  • 17,714
  • 12
  • 90
  • 109
  • this will work only if your html page contains one 'ul' elemet, what if i've different 'ul' element and i don't want to get id of this. – Prasanna Dec 06 '18 at 14:44
16
var column1RelArray = [];
$('#column1 li').each(function(){
    column1RelArray.push($(this).attr('rel'));
});

or fp style

var column1RelArray = $('#column1 li').map(function(){ 
    return $(this).attr('rel'); 
});
Fresheyeball
  • 29,567
  • 20
  • 102
  • 164
  • 1
    Can you tell me how to retrieve each li element id separately from the array? so that i can use to apply some css to one of the id – Prasanna Dec 06 '18 at 14:55
  • 1
    Please ask a new question in stack overflow. These are not comments, but further questions. – Fresheyeball Dec 08 '18 at 00:55
6

html

<ul class="answerList" id="oneAnswer">
    <li class="answer" value="false">info1</li>
    <li class="answer" value="false">info2</li>
    <li class="answer" value="false">info3</li>
</ul>   

Get index,text,value js

    $('#oneAnswer li').each(function (i) {

        var index = $(this).index();
        var text = $(this).text();
        var value = $(this).attr('value');
        alert('Index is: ' + index + ' and text is ' + text + ' and Value ' + value);
    });
Ahmad Aghazadeh
  • 16,571
  • 12
  • 101
  • 98
5
$('li[rel=7]').siblings().andSelf();

// or:

$('li[rel=7]').parent().children();

Now that you added that comment explaining that you want to "form an array of rels per column", you should do this:

var rels = [];

$('ul').each(function() {
    var localRels = [];

    $(this).find('li').each(function(){
        localRels.push( $(this).attr('rel') );
    });

    rels.push(localRels);
});
Joseph Silber
  • 214,931
  • 59
  • 362
  • 292