06-Keywords
In this module, we'll add more display for our results.
Code Additions
We're going to throw a huge chunk of code at you, and then we'll break it apart by number. Again, note that code has been omitted:
Analysis
Let us start by saying that you should do a lot of experimentation with the code above and play around until you understand it. Yes, follow our notes below, but you should also play around with the code as much as possible. Take it apart and put it back together.
We're doing quite a bit here, but some of it is repeat business. Let's break it down: 1. We've declared a paragraph variable that will append a p
tag to the DOM to be used for some of our JSON data. 2. We're declaring a clearfix variable that will later on append a div
to the DOM. More on that later. 3. We are adding the textContent
attribute to our para
variable. Each result will show this at the start of the p
tag that is created by para
. 4. Now, we have a for loop
inside of our for loop
. We are using this nested loop to iterate over the current
object, specifically the keywords
array for that object. If you look through the JSON results, you'll see that keywords
is a property of the entire object, and it's an array. Here, we iterate through the length of the array for the current result object. 5. As we iterate, we create a <span>
for each keyword. If you don't already know, a <span>
will be an element that will end when the item ends. So, the <span>
of Pizza will start at the P and end at the a. If we were to use a p
tag here, it would cover the entirity of the parent object. 6. The textContent
for each <span>
will be the value found inside the keywords
array inside the JSON object. 7. We append each <span>
to the para
node. 8. Remember that we still have an outer loop and printing the results. Here, we're using the setAttribute
method to target our clearfix
class. It's a class in the CSS file. 9. We add clearfix
& para
as children of article
.
Test
Of course, you want to test the app. This will make the DOM additions a lot more clear when you inspect the 'Elements' tab:
Notice how when you do a search, clearfix
, para
, and <span>
elements have been appended to the DOM.
Required Experimentation
In order to understand the <span>
element, do the following. Go inside the new for loop
and change the <span>
to a p
. See below:
What happens in your search results when you run the code? What do you see in the 'elements' tab in Chrome tools?
Whenever you finish, go ahead and change it back to <span>
.
Last updated