This code n creates a <li> with the value specified in the function, what am I doing wrong?

Asked

Viewed 51 times

0

<html>
    <head>
        <link href="css.css" rel="Stylesheet" type="text/css"/>
    </head>
    <body>
        <script>


            function apresente()

            {
                var newEl = document.createElement('li');
                var newText = document.createTextNode('breno');
                newEl.appendChild(newText);
                var position = document.getElementsByName('ol')[0];
                position.appendChild(newEl);
            }



        </script>

        <form>
            <input type="submit" value = "Enviar" onclick="apresente()"/>
        </form>

        <ol>
            <li></li>
        </ol>

    </body>
</html>
  • 2

    your tag shouldn’t be like this: <ol name="ol">? or change the javascript: var position = document.getElementsByTagName('ol')[0];?

  • @Brenoricardo some of the answers presented the solution to your problem?

3 answers

1

There are two points here, first the button is of type submit that will execute the sending of the form, which by not having an address set to action, will cause only the refresh of the page and "nor run" your Javascript. Then the correct method would be document.getElementsByTagName().

You can change the input type to button or add a Return to your method if you are going to implement some other rule where you must submit the form in some condition.

function apresente()

{
  var newEl = document.createElement('li');
  var newText = document.createTextNode('breno');
  newEl.appendChild(newText);
  var position = document.getElementsByTagName('ol')[0];  
  position.appendChild(newEl);
  
  //não vai submeter o formulário até que seja true;
  return false;
}
<html>
<body>
  <form>
    <input type="submit" value="Enviar" onclick="return apresente()" />
  </form>
  <ol>    
  </ol>
</body>
</html>

0

Is there an element with the name ol in his GIFT?

If you want to append an element with the tag ol should wear getElementsByTagName, nay getElementsByName. Out queries possibly returning null, there is nothing wrong with the code.

0

Where has:

var position = document.getElementsByName('ol')[0];

Should be:

var position = document.getElementsByTagName('ol')[0];

Testing here

Browser other questions tagged

You are not signed in. Login or sign up in order to post.