js_dom_cheatsheet (1)
js_dom_cheatsheet (1)
4. Removing Elements
1. parentElement.removeChild(childElement) - Removes a child element
from the parent.
parentElement.removeChild(childElement);
5. Event Handling
1. element.addEventListener(event, function) - Adds an event listener to
an element.
element.addEventListener('click', function() {
alert('Element clicked!');
});
2. element.removeEventListener(event, function) - Removes an event
listener from an element.
element.removeEventListener('click', handlerFunction);
6. Traversing DOM Elements
1. element.parentNode - Selects the parent node of the element.
var parent = element.parentNode;
2. element.children - Returns a collection of the child elements of an
element.
var children = element.children;
3. element.firstChild / element.lastChild - Selects the first or last child of
an element.
var firstChild = element.firstChild;
var lastChild = element.lastChild;
4. element.previousSibling / element.nextSibling - Selects the previous or
next sibling of an element.
var prev = element.previousSibling;
var next = element.nextSibling;
7. Classes
1. element.classList.add(className) - Adds a class to the element.
element.classList.add('newClass');
8. Form Elements
1. inputElement.value - Gets or sets the value of an input element.
var value = inputElement.value;
inputElement.value = 'New value';
2. inputElement.checked - For checkboxes or radio buttons, checks if the
input is checked.
var isChecked = inputElement.checked;
3. selectElement.options - Returns the collection of options in a select
dropdown.
var options = selectElement.options;
9. Events
1. event.target - Refers to the element that triggered the event.
element.addEventListener('click', function(event) {
console.log(event.target);
});
2. event.preventDefault() - Prevents the default behavior of the event.
event.preventDefault();
3. event.stopPropagation() - Stops the event from bubbling up to parent
elements.
event.stopPropagation();