Monday, September 17, 2018

JavaScript - Document Object Model - Query Selectors - Practice

Consider the following body code:

<body>
<ul>
  <h1 id="firstId">hey there</h1>
  <li ><a href="#">Link 1</a></li>
  <li class = "dimple">full</li>
  <li class = "pimple">ness</li>
  </ul>
</body>

Using query selectors on it:

document.querySelector("a").style.backgroundColor = "red";

.. this will change the background of the first anchor tag to red.

document.querySelector(".pimple").style.backgroundColor = "red";

.. this will change the last list item to red color - since it is having the class = pimple.

Since, .pimple class is the third list item. We can also select it using:

document.querySelectorAll("li")[2].style.backgroundColor = "red";

Now, if I want to highlight the link:
document.querySelector("li").firstElementChild.style.backgroundColor = "red";

If I want to change the text of the link:

document.querySelector("li").firstElementChild.textContent = "Its a Link";


No comments:

Post a Comment