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

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
195,639 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
8,730 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.