Javascript – DOM API access and change the style and content of an HTML element

DOM (Document Object Model) can be used to modify HTML elements and CSS styles on the fly. The DOM API is accessible through the document property.

Access HTML elements

  • querySelector(selector) – returns the first element
  • querySelectAll(selector) – returns a collection of HTML elements
, <span>Javascript – DOM API access and change the style and content of an HTML element</span>, KandZ
, <span>Javascript – DOM API access and change the style and content of an HTML element</span>, KandZ
  • getElementById(id) – same as querySelector()
  • getElementByTagName(tag)
  • getElementsByClassName()
, <span>Javascript – DOM API access and change the style and content of an HTML element</span>, KandZ

Change the style

If you want to modify the style on an element, you have to use the style attribute. Then change the CSS property by removing and make capital the next letter. Exampes:

  • text-align => textAlign / style.textAlign
  • margin-left => marginLeft / style.marginLeft
, <span>Javascript – DOM API access and change the style and content of an HTML element</span>, KandZ

Change the content

If you want to change the content of an element, then you can use innerHTML or textContent

, <span>Javascript – DOM API access and change the style and content of an HTML element</span>, KandZ

103510cookie-checkJavascript – DOM API access and change the style and content of an HTML elementJavascript – DOM API access and change the style and content of an HTML element

Related posts