Search code examples
javascriptjqueryhtmlinnerhtml

Modify innerHTML of a child div


I am new to JavaScript. What I am trying to do is make a div and inside of it there will be another div. Within my script code I am trying to create new instances of that div using factory function if that is the right name for it, and then change the innerHTML of the child div if that is possible. Thanks in advance.

<div class = "loopBlock"  style="width:350px;">
    <fieldset>
        <legend style="color:black;font-weight:bold;">While Loop</legend>
        <table>
            <tr>
            <td>Condition:</td>
            <td><input type="text" /></td>
            </tr>
        </table>

        <div class = "codeDivClass" id = "codeDiv">
            HelloWorld!
        </div>
    </fieldset>
</div>


<script>
    var loopDiv = document.getElementsByClassName("loopBlock");
    var loopi =1;

    function loopObject(){
        var loopDivObject = document.createElement("div");
        loopDivObject.innerHTML = loopDiv[0].innerHTML;
        loopDivObject.className = "loopBlock";
        loopDivObject.id = "loopBlock"+loopi;
        loopi++;    
        return loopDivObject;
    };

    var functionCodeDiv = document.getElementById("codeDiv");

    for (i=0; i<5; i++){
        var tempLoop = loopObject();
        functionCodeDiv.appendChild(tempLoop);
        var id = "loopBlock"+i+1;
        document.getElementById(id).getElementsByTagName('div')[0].innerHTML = "bye";
    }

</script>

Solution

  • Didn't really get how it should work, but I'm sure I've found a mistake.

        var id = "loopBlock"+i+1;
    

    you have to replace with:

       var id = "loopBlock"+(i+1);
    

    Example i is 2.

    In first case you get: "loopBlock21"

    In second (my) case, you'll get "loopBlock3"