Search code examples
javascriptjqueryfadeoutchildren

Selecting all children of an element and fadeing them out using jQuery?


I am using the following HTML code:

<!DOCTYPE html>
<html>
<head>
    <title>Project Quiz</title>
    <link rel="stylesheet" type="text/css" href="z/baseCss.CSS">
    <script src="/jquery-1.9.1.min.js"></script>
    <script src="/baseJS.js"></script>
</head>
<body>

<div id=header></div>
<div id=contain>
    <h1>Welcome to my web application</br>
  Please enter your name, click 'continue' and have fun</h1>
    <form>
        <input type="text" id="name" value="John Doe"/>
    </form>
    <div class="awesome">Continue</div><br/>
</div>
<div id=footer></div>

</body>
</html>

and a code of jQuery:

$(document).ready(function(){
    $("input")
        .focus(function(){
        $(this).css('outline-color','#559FFF');
        $(this).blur(function(){
            $(this).css("outline-color","#FF0000");
        });
    });
    $("input").click(function(){
     var value = $(this).val(function(){
         $(this).html("");
      });
    });
    $(".awesome").click(function(){
        b._slide(1000);
    });
    var b = $("div:nth-child(2)");
    alert(b);
});

My problem is that I can't figure it out how to select all children of <div id="contain"> and just make them fade out when I click my div button which is the one with the "awesome" class.

This is what I have tried so far:

$(".contain").each(function(){
    $(this).fadeOut(1000);
});

but it didnt work also i tried: 
$(".contain").children(function(){
    $(this).fadeOut(1000);
});

Same result here.

What am I doing wrong? I only need to fadeOut the content of <div id="contain"> and keep everything else the same as it is.


Solution

  • You need to use:

    $("#contain").children().fadeOut(1000);
    

    Your attempts were wrong because:

    $(".contain").each(function(){ $(this).fadeOut(1000); });
    

    Selects all the elements with class .contain and hides them

    $(".contain").children(function(){ $(this).fadeOut(1000); });
    

    Selects the elements with class .contain, and then you're passing a function to .children() which it does not handle.

    Note, in your case contain is an ID and not a class.