DOM Manipulation (Javascript)

How to manipulate the HTML DOM using Javascript.

Elements

Alteration

<!-- beforebegin -->
<p>
  <!-- afterbegin -->
  foo
  <!-- beforeend -->
</p>
<!-- afterend -->

Insertion

Duplication

Search

DOMParser

The DOMParser allows you to parse HTML in as a string, returning an HTMLDocument object. This allows you to interact with the DOM elements and alter them much more simply and easily than using regex or find/replace in a text-editor.

The DOMParser operates very similarly to jQuery's ability to parse HTML in as a string within $('<input>'). The difference is that DOMParser returns an HTMLDocument instead of a jQuery object.

Importing Plain Text

const parser = new DOMParser();
const htmlDoc = parser.parseFromString(input, 'text/html');

Exporting Plain Text

You can return each of the top level elements (head, body) as plain text using innerHTML.

return htmlDoc.body.innerHTML;

References

  1. https://developer.mozilla.org/en-US/docs/Web/API/DOMParser
  2. https://api.jquery.com/jQuery/
  3. https://www.udemy.com/course/modern-javascript-from-the-beginning/learn/lecture/8757274
  4. https://gomakethings.com/how-to-copy-or-clone-an-element-with-vanilla-js/
  5. https://stackoverflow.com/questions/4106809/how-can-i-change-an-elements-text-without-changing-its-child-elements
  6. https://developer.mozilla.org/en-US/docs/Web/API/Element/insertAdjacentHTML
  7. Shadow DOM and accessibility: the trouble with ARIA | Read the Tea Leave

Last modified: 202401040446