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 jQuery Basics Understanding jQuery Events and DOM Traversal Adding New Elements to the DOM

Adam Lyles Kauffman
Adam Lyles Kauffman
14,012 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
229,788 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,636 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.