Common JavaScript “Element exception” cases
JavaScript provides a variety of built-in functions and properties to manipulate HTML elements. However, not all of these functions and properties can be applied to all elements.
In some cases, you may encounter exceptions when attempting to access or modify certain elements.
Here are a few examples of common JavaScript element exception cases:
1). Accessing a non-existent element:
If you try to access an element that doesn’t exist in the DOM, JavaScript will throw an error. Here’s an example:
const element = document.getElementById('non-existent-element');
console.log(element); // null
element.style.backgroundColor = 'red';
// TypeError: Cannot set property 'backgroundColor' of null
In this case, getElementById
returns null
because there is no element with an ID of "non-existent-element." When we try to set the background color of element
, JavaScript throws a TypeError
because element
is null
and doesn't have a style
property.
2). Accessing a non-standard property:
Some HTML elements have properties that are not part of the standard DOM API. If you try to access one of these properties, you may get an exception. For example:
<marquee id="my-marquee">Hello, World!</marquee>
const marquee = document.getElementById('my-marquee');
console.log(marquee.scrollAmount); // 6
console.log(marquee.direction); // "left"
marquee.foo = 'bar'; // no exception
console.log(marquee.foo); // "bar"
console.log(marquee.nonExistentProperty); // undefined
marquee.nonExistentProperty = 'hello'; // no exception
In this example, we’re accessing the scrollAmount
and direction
properties of a <marquee>
element. These properties are not part of the standard DOM API, but are supported by most browsers.
We can also set a custom property foo
on the marquee
element, which doesn't throw an exception. However, when we try to access a non-existent property nonExistentProperty
, we get undefined
.
3). Modifying a read-only property:
Some properties of HTML elements are read-only, which means they can’t be modified. If you try to set the value of a read-only property, you may get an exception. For example:
<input id="my-input" type="text" value="Hello, World!" readonly>
const input = document.getElementById('my-input');
console.log(input.value); // "Hello, World!"
input.value = 'Goodbye, World!'; // no exception
input.readOnly = false;
input.value = 'Hello, World!';
// TypeError: Cannot assign to read only property 'value'
//of object '#<HTMLInputElement>'
In this example, we’re accessing the value
property of an <input>
element. This property is read-only because the input has the readonly
attribute. We can still read the value of input.value
, and we can set the value to a new string.
However, when we try to set input.readOnly
to false
, we get a TypeError
because the value
property is now read-only and can't be modified.
4). Modifying a property of an undefined element:
If you try to modify a property of an element that hasn’t been defined or created yet, you’ll get a TypeError
or an Uncaught ReferenceError
. Here's an example:
const newDiv = document.createElement('div');
newDiv.id = 'new-div';
document.body.appendChild(newDiv);
const undefinedElement = document.getElementById('non-existent-element');
undefinedElement.style.backgroundColor = 'blue';
// Uncaught TypeError: Cannot read property 'style' of null
In this example, we first create a new div
element with an ID of "new-div" and append it to the body
of the HTML document. Next, we try to access an element with an ID of "non-existent-element" which doesn't exist in the HTML document. When we try to set the backgroundColor
property of undefinedElement
, we get an Uncaught TypeError
because undefinedElement
is null
and doesn't have a style
property.
5). Manipulating a DOM element during a loop:
When looping through a set of DOM elements, it’s important to be careful about manipulating those elements inside the loop. This is because any changes made to the DOM can cause the loop to behave unexpectedly. Here’s an example:
<ul id="my-list">
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>
const list = document.getElementById('my-list');
const items = list.getElementsByTagName('li');
for (let i = 0; i < items.length; i++) {
list.removeChild(items[i]);
}
In this example, we’re removing all of the li
elements from the ul
element using a loop. However, each time an li
element is removed, the items
array is re-indexed.
This means that the loop skips over the next li
element in the list, causing some items to be skipped over and not removed from the list. To avoid this, you can loop through the list of items in reverse order:
const list = document.getElementById('my-list');
const items = list.getElementsByTagName('li');
for (let i = items.length - 1; i >= 0; i--) {
list.removeChild(items[i]);
}
In this updated example, we loop through the items
array in reverse order, starting from the last item and working our way backwards. This ensures that each item is properly removed from the list, without skipping over any elements.
These are just a few more examples of common JavaScript element exception cases. By being aware of these potential pitfalls and taking steps to avoid them, you can write more robust and error-free JavaScript code when working with HTML elements.