Working With Elements in Javascript
Once we have grabbed an element using document.querySelector or grabbing an item from a NodeList after document.querySelectorAll, we then can modify the element using different properties and functions on this HTMLElement object.
I'm Superman
For this page, let's assume we have a superman element:
var superman = document.querySelector('.superman');
The
supermanelement is at the bottom right of this screen and can be modified after each example.
innerHTML
The first property on every HTMLElement object is the innerHTML property.
This property allows us to inspect the current contents of an element OR change the text shown.
alert(superman.innerHTML);
If we assign the innerHTML property, we can change the text of the HTMLElement:
superman.innerHTML = `Changed`;
style
On all elements, there is a style object that allows us to see modify the inline styles for the current element.
Changing these allows let's us make incremental changes to the style of elements.
superman.style.color = `red`;
superman.style.background = `blue`;
NOTE the JS HTMLElement style object should be used for small changes where dynamic data may be needed.For larger changes or transitions, we may want to use classes instead so that all changes can be kept in one spot in our CSS instead of leaving brittle changes in our JS.