Changing Content
- innerHTML: Gets or sets the HTML content inside an element.
element.innerHTML = '<p>New Content</p>';
- textContent: Gets or sets the text content of an element.
element.textContent = 'New Text';
- innerText: Similar to textContent but takes into account CSS styling.
element.innerText = 'New Text';
Changing Attributes
- getAttribute(): Gets the value of an attribute on the specified element.
const value = element.getAttribute('src');
- setAttribute(): Sets the value of an attribute on the specified element.
element.setAttribute('src', 'newImage.jpg');
- removeAttribute(): Removes an attribute from the specified element.
element.removeAttribute('src');
Changing Styles
- Using the style Property: Directly manipulate an element's inline styles.
element.style.color = 'red';
element.style.fontSize = '20px';
Using classList Methods:
add: Adds a class to an element.
element.classList.add('newClass');
- remove: Removes a class from an element.
element.classList.remove('oldClass');
- toggle: Toggles a class on an element.
element.classList.toggle('activeClass');
- contains: Checks if an element contains a specific class.
element.classList.contains('someClass');
Creating and Inserting Elements
- createElement(): Creates a new element.
const newElement = document.createElement('div');
- appendChild(): Appends a child element to a parent element.
parentElement.appendChild(newElement);
- insertBefore(): Inserts an element before a specified child of a parent element.
parentElement.insertBefore(newElement, referenceElement);
- insertAdjacentHTML(): Inserts HTML text into a specified position.
element.insertAdjacentHTML('beforebegin', '<p>Before</p>');
element.insertAdjacentHTML('afterbegin', '<p>Start</p>');
element.insertAdjacentHTML('beforeend', '<p>End</p>');
element.insertAdjacentHTML('afterend', '<p>After</p>');
- append() and prepend(): Inserts nodes or text at the end or beginning of an element.
parentElement.append(newElement, 'Some text');
parentElement.prepend(newElement, 'Some text');
Removing Elements
- removeChild(): Removes a child element from a parent element.
parentElement.removeChild(childElement);
- remove(): Removes the specified element from the DOM.
element.remove();
Top comments (0)