Restricting JavaScript from changing properties of HTML elements

We easily can modify some allowed attributes of an HTML element using JavaScript as follows:
html_element_object.attribute=new_value;

e.g.

this.name,

document.GetElementById('elem_id').value,

document.GetElementsByName('div')[3].innerHTML and many more…

But sometimes it is necessary to restrict such programmatic modification of the properties of an HTML element for consistency with the operation needed. In that case you need to execute the following JavaScript:

Object.freeze(html_element_object);

Check the DEMO or Execute the following code:

<div id='div1' style="border:1px solid green">1</div>
<button onClick="Object.freeze(document.getElementById('div1')); alert('The div is now frozen. No modification will be allowed through script.')" title="click to freeze the div">Freeze div</button>
<button onClick="try{document.getElementById('div1').innerHTML+=1; if(Object.isFrozen(document.getElementById('div1')))alert('div is frozen; Modification of innerHTML not allowed.')} catch(e){alert(e);}">Change innerHTML</button>

References:

Object.freeze(obj)

Object.isFrozen(obj)

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s