Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript DOM Scripting By Example Improving the Application Code Refactor 1: Create List Items

It's possible create element and append child in just one function?

It's created two functions one to create element and another to append, it's possible create one function that create and append the element?

2 Answers

I don't think there is a function for this, but you can do it in one line:

document.querySelectorAll("body")[0].appendChild(document.createElement("p"));

this creates a paragraph and appends it to the body. This isn't recommended because now you cant easily add content to the p tag, or if later you'd want to delete the p tag from the body, you wouldn't find it easily. so its better so seperate into two parts.

var someP = document.createElement("p");
someP.innerText = "Hello world!";
document.querySelectorAll("body")[0].appendChild(someP);

Thanks, I think it's better create the two functions. Iam just trying to understand better refactoring.