JAVASCRIPT Tutorial
createElement('element_name')
to create a new element, e.g., <p>
.appendChild(element)
adds the specified element to the end of the parent element, e.g., document.body.appendChild(p)
.removeChild(element)
removes the specified element from its parent, e.g., document.body.removeChild(p)
.insertBefore(new_element, reference_element)
inserts the new element before the specified reference element, e.g., document.body.insertBefore(new_p, p)
.setAttribute('attribute_name', 'value')
sets the value of the specified attribute for an element, e.g., p.setAttribute('id', 'my_paragraph')
.getAttribute('attribute_name')
retrieves the value of the specified attribute for an element, e.g., p.getAttribute('id')
.classList.add('class_name')
adds a specified class to an element, e.g., p.classList.add('highlight')
.
classList.remove('class_name')
removes a specified class from an element, e.g., p.classList.remove('highlight')
.classList.toggle('class_name')
adds the class if it doesn't exist or removes it if it does, e.g., p.classList.toggle('active')
.// Create a paragraph and add it to the body
const p = document.createElement('p');
p.textContent = 'Dynamically created paragraph';
document.body.appendChild(p);
// Add a class to the paragraph
p.classList.add('my-class');
// Get the ID attribute of the body element
const bodyId = document.body.getAttribute('id');