To Get (Read) text of an element use .html()
with nothing inside the parentheses
When using .html()
to get html contents, the html contents of the only the first matched element will be returned; see the docs for more info
$(() => {
$('#readHtmlOfParagraph').click(() => {
// get html of the first matched p element
const htmlOfParagraph = $("p").html()
alert(htmlOfParagraph)
})
$('#readHtmlOfContainer').click(() => {
// get html of container
const htmlOfContainer = $(".container").html()
alert(htmlOfContainer)
})
})
.html(newHtml)
with the new Html inside the parentheses$(() => {
$('#addNewNumber').click(() => {
// create a new html element
const htmlOfNewNumber = "<p class='four'> <span>Four</span></p>"
// add new html element to .numbers div
$('.numbers').html(htmlOfNewNumber)
})
})
Notice how the previous paragraphs (<p>one</p>
, <p>two</p>
and <p>three</p>
) were replaced with <p>four</p>
, using .html(newHtml)
will replace the children of the targeted element (in our case the targeted element was .container
)
Later in this lesson, we’ll see how we can add a new element to a list without replacing the exiting elements