1

I'm trying to add a button to my webpage using JavaScript but the console is giving me an error saying:

scripts.js:35 Uncaught DOMException: Failed to execute 'appendChild' on 'Node': Only one element on document allowed.

// 7: Create a <button> element, and set its text to 'Delete'
// Add the <button> inside the '.extra' <div>
const button = document.createElement('button');
button.innerHTML = "Delete";
const buttonPlace = document.getElementsByClassName('.extra')[0];
document.appendChild(button);
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="utf-8">
  <link rel="stylesheet" href="css/main.css">
  <title>Practice Manipulating the DOM</title>
</head>

<body>
  <div class="container">
    <h1></h1>
    <p class="desc"></p>
    <ul>
      <li><input> Play music</li>
      <li><input> Swim</li>
      <li><input> Bike ride</li>
      <li><input> Code</li>
    </ul>
    <div class="extra">
      <p>This is extra content you need to delete.</p>
    </div>
  </div>
  <script src="js/scripts.js"></script>
</body>

</html>

Any idea on what's going on? Thanks for your help!

2
  • button.innerHTML -> button.textContent? Also, you're inserting into html not body... try using document.body.appendChild instead. Commented Feb 26, 2020 at 16:12
  • There should not be a dot in the class name passed to getElementsByClassName(). Commented Feb 26, 2020 at 16:14

1 Answer 1

2

The only element you can put on the document is <html> (which is there by default).

If you want to add a <button> to the page, then you need to add it somewhere else (and that should be as a descendant of the <body> element).

const buttonPlace = document.getElementsByClassName('.extra')[0];

The above looks like a the spot you want to put the button, but you need to append it there and not to the document object.

buttonPlace.appendChild(button);

Note that in CSS, the . indicates a start of a class selector. Your class name does not start with a . character. You'll need to correct that at the point you call getElementsByClassName.

Sign up to request clarification or add additional context in comments.

2 Comments

@Jackson — That what I said.
@Jackson – Yes, that's what I said.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.