1

I want to add a paragraph after every element of type article using the function add in Javascript but it doesn't work . Here is the code I wrote :

<!DOCTYPE html>
<html>

<head>
<meta charset="utf-8">
</head>

<body>
<article> here is one article
</article>
<article> here is the second article
</article>

<script type ="text/javascript">
function add(info)
{
    var art = document.getElementsByTagName('article');
    var par = document.createElement('p');
    par.textContent = info;
    var i;
    for(i in art)
    {
        art[i].appendChild(par);

        }
};
add("ex");
</script>

</body> 
</html>

The ouput I get is : here is one article here is second article ex

Any help would be appreciated ! Thanks!

locket23
  • 71
  • 1
  • 1
  • 7
  • 2
    It works, but you're appending the same created element after every `
    `; which moves it progressively through the DOM until it's moved to its final position (after the last `
    `); instead try appending a clone of the created `

    `.

    – David Thomas Sep 03 '16 at 10:38
  • 1
    you can not append the same element at multiple places. You should create different `p` elements per article. In your case it appears where it is last appended at. – Redu Sep 03 '16 at 10:40

3 Answers3

2

You've created only one Node, and then you try to "insert" it to every article there is. The node doesn't get cloned automatically, so it gets inserted only to the last element on the articles list. You have to clone your original node-to-insert to make this work:

art[i].appendChild(par.cloneNode(true));

(the true flag in cloneNode clones the node recursively, without it you would have to attach the text on each node copy by hand)

A couple of things to note in your example:

  • Your loop for(i in art) is not exactly safe to use, as you don't check if the element referenced is actually an own member of the list (you don't want to reference art's prototype members).
    Instead, you could simply use for(var i = 0; i < art.length; i++).
  • You are actually inserting your paragraphs inside your articles. To properly append elements, there is a SO answer with clear explanation of how to do this without using additional libraries.
Community
  • 1
  • 1
mdziekon
  • 3,531
  • 3
  • 22
  • 32
1

You only ever create one paragraph. Each time you go around the loop you put that paragraph at the end of the article (moving it from wherever it was before).

You need to create the paragraph inside the loop if you want to create more than one of them.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
-1

You are using the same DOM to place each time in loop. So create new DOM in each iteration of loop. Try out following.

<script type ="text/javascript">
function add(info)
{
    var art = document.getElementsByTagName('article');

    var i;
    for(i in art)
    {   
        var par = document.createElement('p');
        par.textContent = info;
        art[i].appendChild(par);

    }
};
add("ex");
</script>