To do this, we use
let getElement = document.getElementById('my-element')
#my-element in the HTML content of your page. If it exists, it will return a
HTMLElement, which will contain an
let getElement = document.getElementById('my-element') console.log(getElement.innerHTML)
Now we can easily get the HTML contents, including text, of
#my-element. Note: if you use
querySelectorAll to select your HTML elements, this will return multiple
HTMLElements - so make sure you are only selecting one.
Setting an HTML elements innerHTML
As well as getting
innerHTML from an element, we can also redefine it as we see fit. For example, below we can set our elements contents to be just an
let getElement = document.getElementById('my-element') getElement.innerHTML = '<h1>Hello World</h1>'
The contents we pass to
innerHTML will be parsed as HTML, and rendered to the user. There are two things you should consider when doing this:
- If, for example, you are doing this via API, and someone can submit contents to appear on the page - you can run into some security problems. Therefore, you need to be careful how you use this, so that you don’t end up with someone hacking and sending random content or malicious code to many users.
- This will replace all contents within the HTML element - which may not be what you want.
Security concerns with using innerHTML
Regarding security concerns, if you are worried about using this method to set HTML, you can use the
setHTML() which will sanatize input and remove any invalid HTML (unlike
innerHTML). It also removes code it deems unsafe. Alternatively, you can use
textContent - however this will not let you add HTML or scripts to a tag.
For basic manipulations where you are in complete control of what is being done,
innerHTML can be used with relatively few concerns. So finally, you want to add content inside your HTML element in addition to what is already there, instead of replacing it while using
innerHTML, you can do something like this:
let getElement = document.getElementById('my-element') getElement.innerHTML = '<h1>Hello World</h1>' + getElement.innerHTML
The above code will add a
<h1> tag above the rest of your content - while still keeping your existing content.
- How to get the Full URL in Express on Node.js