Why doesn't this jquery code work?


#1

Hi there,
I'm on the 3rd exercise, asking me to change the jquery script to fade out the 4th li item. Here is my code:

// Write your jQuery code on line 3!
$(document).ready(function() {
var $target=.li nth-child(4);
$target.fadeOut('fast');
});

I'm asked to create a variable named $target, use the = sign to assign it to the jQuery selector that represents #4 in the ordered list.

I have tried:

var $target=li nth-child(4);
var $target=.li nth-child(4);
var $target=(li nth-child(4));

Sorry... could someone help please?
Thanks!


#2

Hello :smile:

It's always a good idea to take a look at documentation -> https://api.jquery.com/nth-child-selector/

We usually use $ in jQuery to select element / elements. For example:

 $( "ul li:nth-child(2)" )

#3

Thank you and much appreciated! That was helpful.


#4

You're very welcome :panda_face:


#5

Try this one, 100% working -

// Write your jQuery code on line 3!
$(document).ready(function() {
//var $target = $('li:nth-child(4)'); it is also working
var $target = $('#chump'); // to use this one you have to create an <!-- li ID ="chump" -- > in html index tab.
$target.fadeOut('fast');
});

enjoy.. :smile:


#6

The next section helps explain it better(at least for me). I was define variable as var target = '....'; vs var $target = '.....'


#7

I don't understand. I'm sure I'm doing this correctly but it just won't work. I've tried (separately):

var $target = $("li:nth-child(4)");
var $target = $('li:nth-child(4)');

According to the above at least ONE of these should work. I even copied and pasted the above working solution just to make sure there wasn't a syntax error I wasn't seeing. Please help?

EDIT: Slept on it and figured it out! In case anybody else is having the same problem, mine was to do with the scope of the variables. You have to declare the variable INSIDE the function so that it's clear that "li:nth-child(4)" refers to "document". I think you could declare it outside, but you would need different syntax (couldn't figure this out). Anyway cheers.


#8

My problem is same as yours, I have tried locally what you said but I can't find any differeneces.
I declare the cariable outside function.
Here is my js code:

var $target = $('li: nth-child(4)');
$(document).ready(function() {
  $target.fadeOut('fast');
});

#9

You should declare a variable "$target" inside

$(document).ready(function() {

});


#10

This worked for me!

$(document).ready(function() {
$target = $('ol li:last');
$target.fadeOut('fast');
});