03-Link Display

In this module, we'll make the links show up as headings.

Adding an Anchor Element

Let's add more code and break it down afterwards:

function displayResults(json) {
  let articles = json.response.docs;

  if(articles.length === 0) {
    console.log("No results");
  } else {
    for(let i = 0; i < articles.length; i++) {
      let article = document.createElement('article');
      let heading = document.createElement('h2');
      let link = document.createElement('a'); //1

      let current = articles[i]; //2
      console.log("Current:", current); //3

      link.href = current.web_url; //4
      link.textContent = current.headline.main; //5

      article.appendChild(heading);
      heading.appendChild(link); //6
      section.appendChild(article);
    }
  }
};

Here's the analysis of what we've done: 1. We create a link variable that is going to use the a element, the anchor tag which will allow us to create an 'href' link. 2. We create a current variable that holds the data of the current article as we iterate. 3. We log the current data so that we can see it in the console. 4. Since link is an a element, we need to attach an href property to it. current.web_url grabs the hyperlink for the current article out of the json result. This will set the value for the link.href each time we iterate. 5. The text that we'll use in link.textContent is set to the value of current.headline.main, which is part of the json object from the NYT API. You can see this when you drill down into the data:

Screenshot

6. Finally, we call the appendChild method on the heading element again. This will append a link as a child element in the DOM inside of each h2. See the screenshot for orientation:

Screenshot

You should have two things at this point: 1. Here's what you should be seeing by now.

Screenshot
  1. The links that you see are the headings, which should be clickable.

Last updated