2

HTML:

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script src="jQuery/jquery-1.8.2.min.js" type="text/javascript"></script>
<script src="js/script1.js" type="text/javascript"></script>
</head>
<body>

<div>
    <ul>
        <li>One</li>
        <li>Two</li>
        <li>Three</li>
    </ul>

</div>    

</body>
</html>

Script which works:

$(document).ready(function () {
$('li:nth-child(2)').fadeOut('fast');
});

Now I just use a variable to do the same thing and it does not work anymore.

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

Can anyone please tell me the correct syntax. I have just started learning jQuery and know it is probably a simple mistake but I just cannot figure it out. Thanks in Advance. :)

2 Answers 2

3

Put it into the document ready function when the li actually exists:

$(document).ready(function () {
   var $var = $('li:nth-child(2)');
   $var.fadeOut('fast')
});
Sign up to request clarification or add additional context in comments.

2 Comments

thanks, it works now. small doubt, when I declare it outside, doesn't it make it a global variable and hence accessible everywhere?
well, generally yes. But since you are selecting an element that doesn't exist at that time, your variable will always be and stay empty. But yes - you created a global variable :)
1

The variable needs to be assigned inside the $(document).ready(function() { }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.