Tuesday, September 1, 2015

How to remove all childNode by iterating and append it again by iteration on demand

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
    <style>
        p{
            margin-top: 25px;
        }
    </style>
</head>
<body>
<div class="container">
    <div class="row">
        <div class="col-md-4">
            <h1 class="btn btn-success btn-lg" onclick="showHeading()">Heading</h1><br>
            <h1 class="btn btn-warning btn-lg" onclick="showParagraph()">paragraph</h1> <br>
            <h1 class="btn btn-warning btn-lg" onclick="showAll()">Show all</h1>
        </div>
        <div class="col-md-8">
            <div id="main">
                <h1 id="heading">This is heading</h1>
                <p id="paragraph">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Adipisci alias beatae deleniti dolore excepturi iste iusto maxime nesciunt nihil, nisi obcaecati placeat quae similique sit soluta! Nemo praesentium qui quod!</p>
            </div>
            <div id="main2"></div>
        </div>
    </div>
</div>
<script>
    var main = document.getElementById('main');
    var main2 = document.getElementById('main2');
    var all_child = [];
    for(var i = 0; i < main.childNodes.length; i++){
        all_child.push( main.childNodes[i]);
    }
    function removeAll(){
        while(main.hasChildNodes()){
            main.removeChild(main.firstChild);
        }
    }
    function showAll(){
        for(var j = 0; j < all_child.length; j++){
            main.appendChild(all_child[j]);
        }

    }
    function showHeading(){
        removeAll();
        main.appendChild(all_child[1]);

    }
    function showParagraph(){
        removeAll();
        main.appendChild(all_child[3]);

    }
</script>
</body>
</html>

No comments:

Post a Comment

css snippet for blogger code highlighting

code, .code {     display: block;     background: beige;     padding: 10px;     margin: 8px 15px; }