JQuery + Css - dynamically adding css to a list of items

I am wondering if there is a way to select list items to add the css value to the list.

It’s hard to explain, so let me show you an example:

<ul class="list"> <li></li> <li></li> <li></li> <li></li> .... </ul> 

I would like to take a dynamically generated list like this, and

 <ul class="list"> <li style="left:0px;"></li> <li style="left:10px;"></li> <li style="left:20px;"></li> <li style="left:30px;"></li> .... </ul> 

I'm not sure if this is best done using jQuery, or if there is a CSS selector type that I don't know about, it can do it.

If I were using jQuery, I think it might look something like this:

 $('.list > li:nth-child(2)').css('left', '+=10px').next 

But I'm not sure how to clear the rest of the list and keep adding 10px every time. I play the idea of ​​using ".next" and ".prev", but I'm not sure how to do this.

Thanks for your patience, I'm new to jQuery.

+6
source share
2 answers

You can use each and the index parameter as a control. I used the margin on the left here for my example, but obviously just left will work in your case too.

http://jsfiddle.net/nEePk/

 $('li').each( function(index) { $(this).css('margin-left', index * 10); });​ 

As for CSS only means, I don’t think it will be possible. The reason is that there is no math that can be done in actual terms. Of course, you can select each li using the direct selector.

 li ~ li { ... } 
+8
source

It can always do something like the following:

 var left = 0; $('.list > li').each(function() { $(this).css('left', left + 'px'); left += 10; }); 
+3
source

Source: https://habr.com/ru/post/914975/


All Articles