Leo
Leo

Reputation: 580

How to absolute number elements in jquery

I have this kind of list:

<ul id="list">
 <li>Title 1
  <ul>
   <li>Content 1.1</li>
   <li>Content 1.2</li>
   <li>Content 1.3</li>
  </ul>
 </li>
 <li>Title 2
  <ul>
   <li>Content 2.1</li>
   <li>Content 2.2</li>
   <li>Content 2.3</li>
  </ul>
 </li>
</ul>

I want to add an attribute value with its index number in each of the last level of li element, like data-number='1' to data-number='6'.

The first level of li element, where are the titles, should be ignored.

I tryed lots of thing like this:

$('ul#list ul li').each(function() {
    $(this).attr('data-number',$(this).index() + 1);
});

But it returns:

I just matched and added the attribute, I'm not able to make it count 1 to 6.

I can't change the html tags.

Upvotes: 0

Views: 67

Answers (3)

user1956570
user1956570

Reputation: 142

Try it :

var dataList = function() {

var ul1 = $("#list").child("ul:first");
var ul2 = $("#list").child("ul:last");

ul1.each(function(idx) {
    $(this).attr('data-number',idx + 1);
});

ul2.each(function(idx) {
    $(this).attr('data-number',idx + 3);
});

}

Upvotes: 0

Arun P Johny
Arun P Johny

Reputation: 388406

if you want an attribute value - if you want to use the value in some css rules then

$('#list ul li').attr('data-number', function(idx) {
    return idx + 1
});

Demo: Fiddle

or use .data(), if you want to use the value only in some scripts later. This value can be later retrieved by using $(el).data('number')

$('#list ul li').each(function(idx) {
    $(this).data('number', idx + 1)
});

Demo: Fiddle

Upvotes: 1

Mister Epic
Mister Epic

Reputation: 16743

Try this:

$('ul#list ul li').each(function(idx) {
    $(this).attr('data-number',idx + 1);
});

Upvotes: 5

Related Questions