Controlling Content

Once you have successfully found an element using querySelector, you can read or completely overwrite its contents.

1. innerHTML

This property allows you to get or set the HTML code inside an element. If you pass HTML tags in the string, the browser will render them!

Try replacing the text of the first paragraph on this page with bold text:

JS Console

Type: document.querySelector('p').innerHTML = "<strong>I hacked this text!</strong>"

Warning

Be extremely careful when using innerHTML to display data typed by users (like comments). Hackers can inject malicious <script> tags, leading to dangerous XSS (Cross-Site Scripting) attacks!

2. textContent

This is the safe and fast way to insert pure text. It treats everything as normal text and " neutralizes " any HTML tags.

Try the same hack using textContent. You'll see the raw tags instead of bold text:

JS Console

Type: document.querySelector('p').textContent = "<strong>I failed to hack this!</strong>"

3. value

Used exclusively for input fields, like <input>, <textarea>, and <select>.

const input = document.querySelector('input');
alert(input.value); // Reads what the user typed in the box