jbrowne
jbrowne

Reputation: 1

Difficulty with using HTML DOM .createElement(), .setAttributeNode(), and .appendChild() methods

I'm learning how to develop a dynamic webpage and am trying to use HTML DOM to add JS objects but nothing is appearing after several troubleshooting attempts.

I've tried using .createAttribute() instead of .setAttribute() and have carefully read the descriptions of all the methods to make sure I was using them correctly.

<html>
    <body>
        <div id="greeting_section">
        </div>
    <script>
        let greeting_post = document.createElement("P");
        greeting_post = document.setAttributeNode("id","post");
        let greeting_post_text = document.createTextNode("howdy howdy");
        greeting_post.appendChild(greeting_post_text);
        document.getElementById("greeting_section").appendChild(greeting_post);        
    </script>   
    </body>
</html>

I expect it to output "howdy howdy" but nothing appears in my Firefox browser.

Upvotes: 0

Views: 83

Answers (2)

Budi Salah
Budi Salah

Reputation: 333

First: When I ran your code the browser console showed this error

Uncaught TypeError: document.setAttributeNode is not a function

That's the first thing you should do when your code doesn't work, Take a look at the browser console.

Second: in your code greeting_post = document.setAttributeNode("id","post"); you are trying to add id="post" to greeting_post variable which is the p tag put you do it wrong, Your code means change the variable greeting_post to a new value document.setAttributeNode("id","post"); which mean Set attribute id="post" to the document. So, instead of your code, The correct code should go like this:

greeting_post.setAttribute("id","post");

In English this is mean, select greeting_post and set it's attribute to id="post"

So finale, The complete code should be like this:

let greeting_post = document.createElement("P"),
    greeting_post_text = document.createTextNode("howdy howdy");

greeting_post.setAttribute("id","post");
greeting_post.appendChild(greeting_post_text);
document.getElementById("greeting_section").appendChild(greeting_post);

Upvotes: 1

Nick
Nick

Reputation: 16576

It looks like you're overwriting greeting_post. Also, you might just be meaning to use setAttribute instead of setAttributeNode. See below for a working example.

let greeting_post = document.createElement("P");
greeting_post.setAttribute("id","post");
let greeting_post_text = document.createTextNode("howdy howdy");
greeting_post.appendChild(greeting_post_text);
document.getElementById("greeting_section").appendChild(greeting_post);
<html>
    <body>
        <div id="greeting_section">
        </div>
    </body>
</html>

Upvotes: 1

Related Questions