I have a ul with an id portfolioItems. What I want to do is give the first li in portfolioItems a margin-left of 0.

I've searched all over google and cannot find the right way to target the first-child.

Note: I came across these sites, along with a few others, but I was not able to get them to work. http://docs.jquery.com/Selectors/firstChild http://docs.jquery.com/Selectors/first

5 answers

0
points
This was chosen as the best answer

Assuming that you have markup like this:

<ul class="portfolioItems">
   <li>foo</li>
   <li>bar</li>
</ul>

Then this JS will work:

$(".portfolioItems li:first").css("margin-left",0);
Answered about 7 years ago by Eli Cochran
  • Yeah thats the code I had but it doesnt work. My HTML: <ul id="portfolioItems"> <li class="web"> ... </li> <li class="print"> ... </li> <li class="clothing"> ... </li> </ul> My JQuery: $('#portfolioItems li:first').css('margin-left','0px'); I tried changing the Jquery code for the '0px' to 0, '0'... but none of them worked. If I take off the :first the code works. Also, the reason I dont just target the first li by its class is because I have jquery code that changes the order of the li. Stephen Cronin about 7 years ago
  • I posted my example to my server: http://elicochran.com/first-child-test.html. Give it a try. I suspect that there is something else happening with your code. For me to get the margin to change, I had to add a margin to the default <li>. Eli Cochran about 7 years ago
danwellman 5600
1
point

try $('#portfolioItems').children(':first').css('margin-left','0px');

Answered about 7 years ago by danwellman
0
points

bad post

Answered about 7 years ago by Stephen Cronin
0
points

Maybe you should try try $('#portfolioItems').children(':first').css('marginLeft',0);

I think you can't use short hand syntax with this syntax unless you using it with JSON like

$('#portfolioItems').children(':first').css({'margin-left':'0px'});

Answered about 7 years ago by Reungyos Vorajenwanich
0
points

You can try $('#portfolioItems').children('li:first').css('margin-left', '0px');
It should work this way :)

Answered about 7 years ago by Bogdan Constantinescu