🟨JavaScript DOM manipulation
making changes to the HTML with JavaScript
Finally, now for some "real", "internet-y" stuff!
Manipulating text (innerHTML
or textContent
or innerText
)
innerHTML
or textContent
or innerText
)We can use the innerHTML
propertyt to manipulate the content of each DOM object:
If we load up index.html
the entire webpage will show just:
...as we have just replaced the entire document's body to consist of only that string!
If the manipulation of text comes from public user input, we should use textContent
in place of innerHTML
as letting a public user "inject" HTML might cause problems! The textContent
will only accept a plain string ;)
innerText
example
innerText
exampleAnother property related to innerHTML
and textContent
is: innerText
which returns only the visible non-HTML text within an HTML element:
textContent
example
textContent
exampleMeanwhile, textContent
would return both the visible (non-hidden
) and non-visible (hidden
), non-HTML text of an HTML element:
innerHTML
example
innerHTML
exampleFinally, for the sake of completeness, we can contrast the above two samples with innerHTML
:
There also exists an outerHTML
property which also returns the tag which references it!
Manipulating objects (getElementById
)
getElementById
)Now that we know how to manipulate the document's body, we should know how to manipulate its objects:
Loading up index.html
the webpage will display:
Note that it will replace only the first <div>
because we specified to get the <div>
with the id
of app
and not bar
Creating and appending objects (appendChild
and createElement
)
appendChild
and createElement
)We can:
create elements with the
document.createElement
functioninsert content by using
innerText
ortextContent
append them using the
document.body.appendChild
function
...and we can pass the former as an argument to the latter:
Selecting and removing objects (querySelector
and removeChild
)
querySelector
and removeChild
)Likewise, we can:
point to an element with
document.querySelector
querySelector
takes one String parameter that resembles the notation of the CSS selector, e.g..my-class
,#anId
,section.section-blue
delete objects from the DOM using
document.body.removeChild
Setting element attributes (setAttribute
)
setAttribute
)As well, we can create and update element attributes given an Element
:
Last updated