Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript JavaScript Loops, Arrays and Objects Tracking Multiple Items with Arrays Build a Quiz Challenge, Part 2 Solution

Enemuo Felix
Enemuo Felix
1,895 Points

document.getElementById() & innerHTML

I can't seem to understand what this actually does because it doesn't really make any noticeable change to the code challenge. Every the runs pretty the same before and after they were included in the code. I have checked all questions and answers by the commubity but it's all grammar after grammar, nobody really explains it the way a newb should understand, i'm talking about someone who just started learning how to code with JS. Anyone? Jennifer Nordell Steven Parker

Enemuo Felix
Enemuo Felix
1,895 Points

Thanks Guys, will do that in a jiffy!

3 Answers

Steven Parker
Steven Parker
231,269 Points

:bell: Hi, I got your request. At first look, I thought Jennifer had you covered, but there still seems to be some confusion. So your rephrased question is: "why then does he need the <ol></ol> and <li></li> tags for since the print function have already covered that by fetching styles from css and HTML?"

First, let me point out that the JavaScript code shown here does not do anything with styles. It just builds elements, and if those elements have any styles applied, that will come from the CSS file (not shown here).

Then, the reason for adding the tags is to convert the items in the array (which are just names) into HTML code to display them as an ordered list. The ordered list is part of the document structure.

Does that clear it up?

Enemuo Felix
Enemuo Felix
1,895 Points

Thanks for you answers. I'm sorry, i was away from my PC for some time so I couldn't follow up with my the thread.

So, if I'm to get my understanding rephrased, the document.getElementById() simply manipulates the HTML by using the structure (element) of the specified HTML id to run the argument passed to it by the coder. This structure maybe font color or something else.

Secondly, using my above quiz solution as a reference, does the document.getElementById() make any visible changes to the code when it's previewed because I didn't notice any difference even when the print function was using the document.write method because the code still ran either way?

Jennifer Nordell
seal-mask
.a{fill-rule:evenodd;}techdegree
Jennifer Nordell
Treehouse Teacher

Hi there! I don't know how else to say it really, other than document.getElementById returns the element with that ID. In this case, we had a div with that ID. If it'd been a paragrph, it would have returned that paragraph with that id. Getting the element by ID doesn't in and of itself manipulate the HTML, but only selects part of the HTML.

As for your second point, it would depend on where you were using the document.write. If the document.write didn't specify where it would be written then it would inherit the style of the body. By using this, you say to put all the list items and ordered lists in the output div. If your body had a background color of white and black text, then your items would be in black on a white background. But if your output div had a background of red and had white text and you told it to select the output div and write there, then your lists would be in something with a red background and be printed in white text.

You might consider going into the CSS and changing the output div to have exactly those rules with a red background and white text. Try again with your document.write and try this solution again. If there are any differences it should be immediately visible.

On a side note, after looking at your profile, I notice that you have not taken any HTML nor CSS courses. Much of JavaScript is about manipulating HTML and CSS. This is going to be infinitely easier to understand if you have a very solid understanding of HTML and CSS.

Steven Parker
Steven Parker
231,269 Points

Just to be clear, document.getElementById() does not manipulate the HTML or make any visible changes to the code by itself. All it does is give you a reference that other code can use to examine and/or modify the page.

On the other hand, document.write() puts new content onto the page.

Enemuo Felix
Enemuo Felix
1,895 Points

So Steven Parker what it actually does is that it 'fetches' the elements i.e font color, size etc of the id we referenced from the HTML and this element will modify the argument we pass through it in our code. So our argument will have the same element such as the id in the HTML?

Steven Parker
Steven Parker
231,269 Points

It might be more correct to say that it fetches a reference to the element. This reference can then be used by later code to access the properties of that element that affect things like color and size. And yes, the argument to getElementById is a string containing the same value as the ID property (as given in the HTML) of the element you want to work with.

Enemuo Felix
Enemuo Felix
1,895 Points

I appreciate your help Steve, I think i now get some part of it . Will check other sources to get more or rather will fully understand it when i go through the CSS and HTML courses

Michael Hulet
Michael Hulet
47,913 Points

I think Steven and Jennifer have you covered pretty well for the explanation of what's going on, but I do have some advice. If I were you, I would drop the JavaScript courses right now and learn HTML and CSS if you don't know them already. JavaScript was made to manipulate HTML and CSS, so if you're not familiar with them, you're gonna get lost pretty frequently with front-end JavaScript

Steven Parker
Steven Parker
231,269 Points

I also agree that you might benefit from taking the courses in a different order. I recommend the Front End Web Development track, which will eventually get back to the course you're doing now.

Jennifer Nordell
seal-mask
STAFF
.a{fill-rule:evenodd;}techdegree
Jennifer Nordell
Treehouse Teacher

Hi there! I saw that you wanted me to answer this, but I'm afraid I need a little clarification. The video you've linked to contains the second part of the challenge which was to also print out which questions the user got correct and which they didn't. But the solution to the first challenge only prints to the screen how many questions the user got correct. So, from my perspective, there should have been a fairly significant increase in the amount written to the document.

As far as the document.getElementById(), this looks through the document for a tag with id="output". Remember, ID's are unique on a page. You may not have more than one element with the same ID on any given page. In the HTML is a <div id="output">. The document.getElementByID('output') returns that element. It is then assigned to the variable outputDiv.

The next line outputDiv.innerHTML= message works like this. Now because we've already assigned the element with the id of "output" to this varaible, we don't have to get it again. We can access that element and its properties by using outputDiv. We call the print function and then send in the string stored in message. The innerHTML is a property of an element that contains a string. It might be blank now, and it might not. So when we set it in this way, it will erase anything that's already there and replace it with the new string, which in this case, is the string we sent in named message.

I hope this helps, but let me know if you have further questions! :sparkles:

Enemuo Felix
Enemuo Felix
1,895 Points

I'm so sorry if i'm giving you a had time, maybe something got wrong along the way. I was actually referring to the "Build a quiz challenge solution part 2" by Dave and here's the link. I'm going to post my own solution of the challenge next for better understanding of the question https://teamtreehouse.com/library/javascript-loops-arrays-and-objects/tracking-multiple-items-with-arrays/build-a-quiz-challenge-part-2-solution

Enemuo Felix
Enemuo Felix
1,895 Points

I'm was asking about the use and impact of the getElementById() introduced by Dave in the print function here

function print(message)
var outputDiv = document.getElementById('output');
outputDiv.innerHTML += message

Here is my own solution for the challenge for better reference

function print(message) {
  var outputDiv = document.getElementById('output');
  outputDiv.innerHTML += message;
}
function buildList(array) {
  var htmlList = '<ol>';
  for(var q = 0; q < array.length; q += 1) {
    htmlList += '<li>' + array[q] + '</li>';
  }
  htmlList += '</ol>';
  return htmlList;
}
var html;
var count = 0;
var questions = [
 ['What letter is the first alphabet?', ' a'],
 ['Who won the last world cup?', 'germany'],
 ['What is the capital of germany?', 'berlin']
];
var correctAnswer = [];
var wrongAnswer = [];
for (var i = 0; i < questions.length; i +=1) {
  var userInput = prompt(questions[i][0]);
  if(questions[i][1].indexOf(userInput.toLowerCase() ) > -1) {
    correctAnswer.push(questions[i][0]);// trying to push the correct input into the correctAnswer array//
    count+=1;
    print
  } else {
    wrongAnswer.push(questions[i][0]);// trying to apply the same with line 16 but this time in the wrongAnswer array//
  }
  html = 'You got ' + count + ' question(s) correctly out of 3';
}
print(html);
print('<h2>You got these question(s) correct ;</h2>');
print(buildList(correctAnswer) );// to print out the correctAnswer to the page with each of them numbered//
print('<h2>You got these question(s) wrong ;</h2>');
print(buildList(wrongAnswer) );//same with line 22//
Jennifer Nordell
seal-mask
.a{fill-rule:evenodd;}techdegree
Jennifer Nordell
Treehouse Teacher

Hi again! Your solution also uses the getElementById and also works. Again, this is specifying where we should add the ordered lists. Imagine for a moment that you had not one, but three divs and all three of them have different sets of CSS rules.

<div id="div1">
</div>
<div id="div2">
</div>
<div id="div3">
</div>

If you did getElementById and then used the innerHTML property on that and set it equal to "Hello there, Enemuo", you would get that text inside the second div. Maybe the divs have some font-color rules like this:

#div1 {
  font-color: black;
}

#div2 {
  font-color: red;
}

#div3 {
  font-color: black;
}

Because you've chosen to write your text inside the div with the id of "div2", all of the text there will be red. You could do a document.write() without specifying where to write it, but then it will inherit the CSS styles for the body.

Does this help? :sparkles:

Enemuo Felix
Enemuo Felix
1,895 Points

Thank you so much Jennifer, I really understand you totally, I think I have problem summarizing my understanding to you. I think i'm mixing up the programming terms(maybe because i'm new to this) .

However, I know it would have been easier for me to understand if i had taken the CSS and HTML courses before humping onto Js. But I have already started Js before I knew about the order, so i figured I should do those after this. I hope the whole thing won't blow up in my face? Thank you once again for your patience

Enemuo Felix
Enemuo Felix
1,895 Points

Thank you again Jennifer for the quick response. I'm sorry if i didn't make my question more clear. I just used the available video link i had to ask the question, but since Dave used the element method in part 1&2 of the challenge. I thought the question still remains valid.

So back to the question, what i understood from your explanation is that the whole element method is simply telling JS to use the same style as the id(output) to style the argument he's to pass through the print function . But if this is the case, why then does he need the <ol></ol> and <li></li> tags for since the print function have already covered that by fetching styles from css and HTML?

Jennifer Nordell
seal-mask
.a{fill-rule:evenodd;}techdegree
Jennifer Nordell
Treehouse Teacher

Hi there! Unfortunately, I still don't know what you mean by "element method". What I can say is that document.getElementById() does not appear anywhere in Dave's code in this video. There is, however, the print function which simply writes the result to the document without specifying where. In the solution here, there were no <ol> or <li> tags.

My explanation had nothing to do with CSS styles. What I was trying to get across was that the getElementById was going to tell it where in the document to write the information.

I feel like I need to know exactly which bit of code you're referring to. I sincerely want to help, but I'm still confused as to what you're asking. I think you might be referring to the unordered list and list items that he adds to the page in the second solution. Keep in mind that before the print(message) happens the ordered list and list items don't exist in the index.html. He uses a function called buildList to build up a string that contains an ordered list and list items. He thien sends this string to the print function which places 2 ordered lists onto the index.html. These of course, get any styles applied by the CSS.

Please know if I can help further or provide specific code that I can address, because unfortunately, I'm still not entirely clear on what you are asking. :sparkles: