DEV Community

Ruxin Qu
Ruxin Qu

Posted on

JavaScript and DOM

  1. .innerHTML provides the access to change the contents of an element; .style provides the access to change the style of an element.
  2. document.body.innerHTML = '<h1>this is a new heading</h1>';
  3. document.getElementById('').innerHTML. = ''; document.getElementsByClassName('')[0].innerHTML = ''; document.getElementsByTagName('')[0].innerHTML = '';
  4. document.body.style.backgroundColor = 'black';
  5. document.body.children[0] refers to the first element in body. document.getElementById('').parentNode represents the parent of the element with id ''
  6. Create an element:
let newHeading = document.createElement('h2');
newHeading.id = 'heading';
newHeading.innerHTML = 'This is a heading';
document.body.appendChild(newHeading);
//Output: add a h2 heading at the bottom of body
Enter fullscreen mode Exit fullscreen mode

7.Remove an element:

let elementToRemove = document.getElementById('sign');
document.getElementById('parent id').removeChild(elementToRemove)
//Output: remove the element with id='sign' from the parent node.
Enter fullscreen mode Exit fullscreen mode

8.Hide an element:
document.getElementById('').hidden = true;
9.Add click:

let element = document.querySelector('.classname');
element.onclick = function(){
  element.style.backgroundColor = 'black';
  element.style.color = 'white';
  element.innerHTML = 'I turn white';
}
//Output: first element with class='.classname' will change color and bicolor and text content once clicked.
Enter fullscreen mode Exit fullscreen mode

Top comments (0)