Monday, September 17, 2018

JavaScript - Document Object Model - Selecting Elements

First the mediocre way:

console.log(document.getElementsByTagName("li"));

This will return an complex object with an array containing all the list elements. 

Now, add the following body code with CSS class names:

<body>
<ul>
<h1 id="firstId">hey there</h1>
  <li class = "simple">Mind</li>
  <li class = "dimple">full</li>
  <li class = "pimple">ness</li>
  </ul>
</body>


The following will list all elements by Class Name:
console.log(document.getElementsByClassName("simple"));

You can also get element by Name:
console.log(document.getElementById("simple"));

Query Selectors: 

There is a best way as well. JavaScript also has querySelectors:
console.log(document.querySelector("li"));

querySelectors use the CSS selectors. Now, if you want to select using the class Name:
console.log(document.querySelector(".simple"));

But, this returns only one element. But, if you want to return all the elements as an array:
console.log(document.querySelectorAll(".simple"));

We can also use the hashtag (#) selector to select by ID:

Add the follow

console.log(document.querySelector("#firstId"));

... this selects element by ID.

After selecting, we can change the background color of the selected element:

console.log(document.querySelector("#firstId").style.backgroundColor="red");

query selector makes it easier as you do not have this chain calls. 










No comments:

Post a Comment