DOM - Element Nodes


Keep in mind that each HTML Element in the preceding list inherits properties and methods from HTMLElement, Element, Node, and Object.

HTML Element Object Properties and Methods (Including Inherited)

• createElement() • tagName • children • getAttribute() • setAttribute() • hasAttribute() • removeAttribute() • classList() • dataset • attributes

https://developer.mozilla.org/en-US/docs/Web/API/element

createElement()

var elementNode = document.createElement('textarea');
// HTMLTextAreaElement() constructs <textarea>

Getting, Setting, and Removing an Element’s Attribute Value

<a href='#' title="title" data-foo="dataFoo" style="margin:0;" class="yes" foo="boo" hidden="hidden">#link</a>
  • removeAttribute() = setAttribute(‘’) = setAttribute(‘null’)
const atts = document.querySelector('a');
atts.removeAttribute('href');
atts.removeAttribute('title');
atts.removeAttribute('style');
atts.removeAttribute('data-foo');
atts.removeAttribute('class');
atts.removeAttribute('foo'); //custom attribute
atts.removeAttribute('hidden'); //boolean attribute
// <a>#link</a>
  • setAttribute()
atts.setAttribute('href','#');
atts.setAttribute('title','title');
atts.setAttribute('style','margin:0;');
atts.setAttribute('data-foo','dataFoo');
atts.setAttribute('class','yes');
atts.setAttribute('foo','boo');
atts.setAttribute('hidden','hidden'); 
//boolean attribute requires sending the attribute as the value too

// <a href='#' title="title" data-foo="dataFoo" style="margin:0;" class="yes" foo="boo" hidden="hidden">#link</a>
  • getAttribute()
console.log(atts.getAttribute('href'));
// #
console.log(atts.getAttribute('title'));
// title
console.log(atts.getAttribute('style'));
// margin:0;
console.log(atts.getAttribute('data-foo'));
// dataFoo
console.log(atts.getAttribute('class'));
// yes
console.log(atts.getAttribute('foo'));
// boo
  • hasAttribute()
console.log(atts.hasAttribute('hidden'));
// true 

Adding and Removing Subvalues to a Class Attribute

<div class="dog"></div>
  • classList.add() & classList.remove()
const elm = document.querySelector('div');
elm.classList.add('cat'); 
elm.classList.remove('dog'); 
console.log(elm.className); //'cat'

Toggling a Class Attribute Value

  • classList.toggle()
elm.classList.toggle('cat'); 
elm.classList.toggle('dog');
console.log(elm.className); //'dog'

Determining Whether a Class Attribute Value Contains a Specific Value

console.log(elm.classList.contains('dog')); 
//logs true





© 2020.11. by creamer

Powered by CREAMer