0

Can someone explain how to appendChild to a parent <div class="..."> and solve this ?

The innerHTML should set the variable str after every <div class='categories'> </div> it created dynamically when you set a value to the texts and press the button "press"

function addField() {
    var categoryValue = document.getElementById("newCateg").value;
    var fieldValue = document.getElementById("newField").value;
// var selOption = document.option[selectedIndex.text];

    var newCategoryNode = document.getElementsByClassName('categories');

    var categoryPart1 = [
        '    <div class="categories">',
        '<input type="checkbox" class="check"/>  <a class="titles">'].join('');

    var categoryPart2 = [
        '</a>',
        '    <hr/>',
        '   <input type="checkbox" class="check"/> ' ].join('');

    var categoryPart3 = [
        '        <input type="text"  />',
        '   <br> </br>',
        '<hr/>',
        '</div>'].join('');

    var str=categoryPart1 + categoryValue + categoryPart2 + "" +       fieldValue + "" + categoryPart3;
    
   
    for (var i = 0; i < newCategoryNode.length; i++) {
        newCategoryNode[i].innerHTML=str;
    }
}
<!DOCTYPE html>
<html>
    
    <body>
        <input type="text" id="newCateg" />
        <input type="text" id="newField" />
        <div class="categories">
            <p class="titles">
                <input type="checkbox" class="check" onchange="checkAll('divID',true,elem)" />FUN</p>
            <hr/>
            <div class="field">
                <input type="checkbox" class="check" />D
                <input type="text" />
                </br>
            </div>
            <input type="checkbox" class="check" />
            <label>S</label>
            <input type="text" id="c1" />
            </br>
            <input type="checkbox" class="check" />
            <label>A</label>
            <input type="text" />
            <hr/>
        </div>
        <input type="button" onclick="addField()" value="Press">
    </body>

</html>
nikolaosmparoutis
  • 440
  • 1
  • 6
  • 15
  • 1
    *appendChild* is for appending DOM elements, not strings. Perhaps you want `node[i].innerHTML = str;` or perhaps `node[i].innerHTML += str;`. – RobG Jan 14 '15 at 03:54
  • alright,then how i append the innerHTML to the parrent class? – nikolaosmparoutis Jan 14 '15 at 03:56
  • Oh, and get rid of the *faux* XML markup style, it's an HTML document. ;-) – RobG Jan 14 '15 at 03:58
  • What do you by "*append*"? Concatenate? – PM 77-1 Jan 14 '15 at 04:00
  • let me explain ..i will edit the code according to RobG – nikolaosmparoutis Jan 14 '15 at 04:04
  • Typo: `document.getElemensByClassName` => `document.getElementsByClassName`. Another typo in your question title. Also, where are you using `newCategory`? –  Jan 14 '15 at 04:07
  • @PM append i mean set the str after the
    – nikolaosmparoutis Jan 14 '15 at 04:16
  • http://stackoverflow.com/questions/4793604/how-to-do-insert-after-in-javascript-without-using-a-library – PM 77-1 Jan 14 '15 at 04:24
  • @RobG: `.insertAdjacentHTML()` Please don't tell people to do `.innerHTML += str;` –  Jan 14 '15 at 04:34
  • everyone says everything here.only god knows who is right or wrong here... i am confused – nikolaosmparoutis Jan 14 '15 at 04:47
  • @squint—that produces a different result to what I was suggesting, but I think it's the outcome the OP wants (i.e. to insert siblings to the div, not content). – RobG Jan 14 '15 at 04:57
  • All here see try to look Mr.Genius and cannot understand 20 simple lines of code about what i want to do... Create dynamically cascading divs which every div takes the values from the two texts...no overwritting but add a div after another div etc. – nikolaosmparoutis Jan 14 '15 at 05:06
  • 2
    everyone is trying to help you here actually.It appears that you are not sure what you are trying to do with your code. – AL-zami Jan 14 '15 at 07:43
  • @RobG: Not sure what you mean. `.insertAdjacentHTML()` is capable of inserting at one of four different positions relative to the element on which it's invoked, one of which would be at the end of its content, like `.appendChild()` does. However it's non-destructive, unlike `.innerHTML += ...` –  Jan 14 '15 at 19:26

3 Answers3

1
<!DOCTYPE html>
<html>

    <body>
        <input type="text" id="newCateg" />
        <input type="text" id="newField" />
        <div class="categories">
            <p class="titles">
                <input type="checkbox" class="check" onchange="checkAll('divID',true,elem)" />FUN</p>
            <hr/>
            <div class="field">
                <input type="checkbox" class="check" />D
                <input type="text" />
                </br>
            </div>
            <input type="checkbox" class="check" />
            <label>S</label>
            <input type="text" id="c1" />
            </br>
            <input type="checkbox" class="check" />
            <label>A</label>
            <input type="text" />
            <hr/>
        </div>
        <input type="button" onclick="addField()" value="Press">
    </body>

    <script>
        function addField() {
                var categoryValue = document.getElementById("newCateg").value;
                var fieldValue = document.getElementById("newField").value;
            // var selOption = document.option[selectedIndex.text];

                var newCategory = document.getElementsByClassName('categories');

                var div = document.createElement('div');
                    div.setAttribute('class', 'categories');

                var a = document.createElement('a');
                    a.setAttribute('class', 'titles');

                var hr = document.createElement('hr');

                var input_check = document.createElement('input');
                    input_check.setAttribute('type', 'checkbox');
                    input_check.setAttribute('class', 'check');

                var input = document.createElement('input');
                    input.setAttribute('type', 'text');

                var br = document.createElement('br');

                var textnode = document.createTextNode(fieldValue);

                div.appendChild(input);
                div.appendChild(a);
                div.appendChild(hr);
                div.appendChild(input_check);
                div.appendChild(textnode);
                div.appendChild(input);
                div.appendChild(br);
                div.appendChild(br);
                console.log(div);

                var node = document.getElementsByClassName('categories');

                for (var i = 0; i < node.length; i++) {
                    node[i].appendChild(div);
                }
            }

    </script>

</html>

hope this could give you idea on how to do it.

you cannot use appendChild to a node using a string it shoud also be a DOM element

you can check on document.createElement and document.createTextNode function

hope it would help you more on your understanding

Oli Soproni B.
  • 2,774
  • 3
  • 22
  • 47
0

According to MDN, Node.appendChild() wants a Node object as its argument. It won't create one from a string of markup, so you'll have to create it yourself.

You can use document.createElement() to create a Node object, then you can set its innerHTML as you like. Once the Node is all set how you want, you can add it to the DOM using appendChild().

Chris Bouchard
  • 806
  • 7
  • 12
  • this is false i can guess .So how i will append a string to a previous div .... var newNode=createElement("div"); newNode=str; for (var i = 0; i < newCategoryNode.length; i++) { newCategoryNode[i].appendChild(newNode); – nikolaosmparoutis Jan 14 '15 at 04:22
  • Your code makes no sense. You create a div, then immediately replace it with a string. – Chris Bouchard Jan 14 '15 at 15:13
0

If you want to use appendChild() mehtod it doesn't work this way.First you have to create a child using element.createElement() method.Now concentrating on your code i encountered some problem. your getElementsByClassName is returning a nodelist containing all the elements having same class.So if you want to grab it provide it an index.As you have only one it's better to provide [0] index to it.

var newCategoryNode = document.getElementsByClassName('categories')[0];

if you don't provide index in getElementsByClassName() you can also access it

 newCategoryNode[0].innerHTMM=str

i removed for loop from you code.If you want to use loop use for...in loop instead as it is a list of object.

var newCategoryNode = document.getElementsByClassName('categories');
               for(key in newCategoryNode){
                   newCategoryNode[key].innerHTML=str;
               }

you haven't defined checkAll() function related to one of your input tag.That surely get you an error.I've modified your code and it might give you the result you want

            function addField() {
   console.log('logged');
                var categoryValue = document.getElementById("newCateg").value;
                var fieldValue = document.getElementById("newField").value;
            // var selOption = document.option[selectedIndex.text];

                var newCategoryNode = document.getElementsByClassName('categories')[0];

                var categoryPart1 = [
                    '    <div class="categories">',
                    '<input type="checkbox" class="check"/>  <a class="titles">'].join('');
  console.log(categoryPart1);
                var categoryPart2 = [
                    '</a>',
                    '    <hr/>',
                    '   <input type="checkbox" class="check"/> ' ].join('');

                var categoryPart3 = [
                    '        <input type="text"  />',
                    '   <br> </br>',
                    '<hr/>',
                    '</div>'].join('');

                var str=categoryPart1 + categoryValue + categoryPart2 +   fieldValue + "" + categoryPart3;
                
                console.log(str);
              
      newCategoryNode.innerHTML =str;
   
     }
        <input type="text" id="newCateg" />
        <input type="text" id="newField" />
        <div class="categories">
            <p class="titles">
                <input type="checkbox" class="check" />FUN</p>
            <hr/>
            <div class="field">
                <input type="checkbox" class="check" />D
                <input type="text" />
                </br>
            </div>
            <input type="checkbox" class="check" />
            <label>S</label>
            <input type="text" id="c1" />
            </br>
            <input type="checkbox" class="check" />
            <label>A</label>
            <input type="text" />
            <hr/>
        </div>
        <input type="button" onClick="addField();" value="Press">
AL-zami
  • 8,902
  • 15
  • 71
  • 130
  • 1
    *"[...] getElementsByClassName is returning an array"*. No it's not, it's returning a `NodeList` or `HTMLCollection`. They can be accessed and iterated over like arrays but they don't have any of the arrays methods. – Felix Kling Jan 14 '15 at 04:56
  • *"i removed for loop from you code.If you want to use loop use for...in loop instead as it is a list of object"* Sorry, but that's completely wrong. He should *not* use `for-in` on this type of collection because it may include other items besides just the elements. The `for` loop is correct. –  Jan 14 '15 at 19:38
  • he can check for 'length' element with an if statement,if you are calling it an issue – AL-zami Jan 14 '15 at 19:43
  • Could be `.length`, could be something else. Either way, his loop was the way to do it; `for-in` is not. Also `for-in` doesn't guarantee numeric order and is slower. There's just no reason to use it on arrays or array-like objects. –  Jan 14 '15 at 20:03