JavaScript/Finding elements/Exercises

From Wikibooks, open books for an open world
Jump to navigation Jump to search

Topic: Locate elements and DOM navigation

We use the following HTML page for the exercises.

<!DOCTYPE html>
<html>
<head>
  <script>
function show() {
  "use strict";
  // ...
}
  </script>
  <style>
    .head_2 {
      display: flex;
      justify-content: center;
    }
    .text, .text_right{
      padding-left: 1em;
      font-size: 1.4em;
    }
    .text_right {
      display: flex;
      justify-content: right;
      padding-right: 1em;
    }
    .button {
      height:1.4em;
      width: 4em;
      margin-top: 1em;
      font-size: 1.2em;
      background-color: Aqua;
    }
  </style>
</head>

<body>
  <h1>An HTML header</h1>

  <h2 class="head_2">An HTML sub-header</h2>
  <div id="div_1">
    <p id="p1" class="text">Paragraph 1</p>
    <ul>
      <li id="one">First item</li>
      <li id="two">Second item</li>
      <li id="three">Third item</li>
    </ul>
    <p id="p2" class="text">Paragraph 2</p>
    <p id="p3" class="text_right">Paragraph 3</p>
  </div>

  <div id="div_2">
    <p id="p4" class="text_right">Paragraph 4</p>
  </div>

  <button class="button" onclick="show()">Go</button>

</body>
</html>



1. Extent the function show in a way that it shows the content of all li elements.

Click to see solution
function show() {
  "use strict";

  const elemArray = document.getElementsByTagName("li");
  for (let i = 0; i < elemArray.length; i++) {
    alert(elemArray[i].innerHTML);
  }
}



2. Extent the function show in a way that it shows the content of all elements of the CSS class text.

Click to see solution
function show() {
  "use strict";

  const elemArray = document.getElementsByClassName("text");
  for (let i = 0; i < elemArray.length; i++) {
    alert(elemArray[i].innerHTML);
  }
  // please note that the third paragraph is not included
}



3. Extent the function show in a way that it shows the content of the second paragraph. Use exclusively getElementsByTagName.

Click to see solution
function show() {
  "use strict";

  // retrieve all 'div'
  const divArray = document.getElementsByTagName("div");
  const firstDiv = divArray[0];
  // navigate again, starting from the first 'div' element
  const pArray = firstDiv.getElementsByTagName("p");
  // show the second 'p' element
  alert(pArray[1].innerHTML);
}