Manipulating Elements

manipulating-elements

Changing Content

  • innerHTML: Gets or sets the HTML content inside an element.
element.innerHTML = '

New Content

';
  • 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', '

Before

'); element.insertAdjacentHTML('afterbegin', '

Start

'); element.insertAdjacentHTML('beforeend', '

End

'); element.insertAdjacentHTML('afterend', '

After

');
  • 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();
Total
0
Shares
Leave a Reply

Your email address will not be published. Required fields are marked *

Previous Post
wasm-+-flutter-web — things-you-need-to-know!

WASM + Flutter Web — Things you need to know!

Next Post
why-brand-publishing-is-the-future-of-marketing

Why Brand Publishing is the Future of Marketing

Related Posts