Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript jQuery Basics Understanding jQuery Events and DOM Traversal Adding New Elements to the DOM

Adam Lyles Kauffman
Adam Lyles Kauffman
13,687 Points

hard time understanding reason behind creating button this way.

im confused as to why we added a button by directly inserting the html into the selector as opposed to using the .html setter method we learned about previously.

//Create the reveal spoiler button const $button = $('<button>Reveal spoiler</button>'); //append to page $('.spoiler').append($button);

i tried //Create the reveal spoiler button const $button = $('<button>Reveal spoiler</button>'); //append to page $('.spoiler').html($button);

but after i click the button it disappears and no text is displayed. it seems the span tag nested inside the p tag with the .spoiler class disappeared.

2 Answers

Steven Parker
Steven Parker
218,571 Points

As Emmanuel pointed out, these two methods do different things. But they also are designed to use different arguments.

The "append" method can take a variety of argument types, including jQuery objects, but the "html" method only takes a string or function argument. Since "$button" is a jQuery object, it is not a suitable argument for use with the "html" method. But it's fine for the "append" method as shown in the video example.

Emmanuel C
Emmanuel C
10,635 Points

The append methods adds the html to whatever is there already. However the html methods replaces the html content completely.

So when you call append itll add that element as a child of the element with class="spoiler" like it was a the beginning of the video. But when you call html, itll remove the html inside the element with class="spoiler" , which was that span element and replace it with the new button element you created in jquery.