Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how can we declare a DOM element as const and still modify it? [duplicate]

Tags:

javascript

dom

I can't figure out why we can change a DOM element even if we are declaring it as a constant.If we are not changing it so what are we really doing? thank you in advance.

const button = document.getElementsByTagName('button')[0];
const domElement = document.getElementsByTagName('div')[0];
button.addEventListener('click', e => {domElement.innerText = "how can I be modified even I am const?"});
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>DOM Example</title>
    
</head>
<body>
    <div>change me</div>
    <button>Change a DOM element </button>
</body>
</html>
like image 801
Firas Omrane Avatar asked Jan 29 '23 20:01

Firas Omrane


1 Answers

const only prevents you from changing what object the variable reference points to. It does nothing to stop you from modifying the object itself.

This would be illegal:

const x = 5;
x = 4; // ERROR

const x = { a: 1 };
x = { b: 2 }; // ERROR

But this is fine:

const x = { a: 1 };
x.a = 5;
like image 129
casieber Avatar answered Feb 01 '23 23:02

casieber