JavaScript JavaScript Loops, Arrays and Objects Tracking Multiple Items with Arrays Useful Array Methods

Max Gerek
Max Gerek
2,718 Points

How would you edit the code to account for the browser update to print each time?

How do you account for the important update?

1 Answer

Bryan Land
Bryan Land
9,327 Points

This all stems around the fact that the browser only renders document.write methods in the DOM after it exits its JavaScript or rendering mode. The only solution is to use a different method of getting the search item to using a button with an event listener. See this example:

HTML:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Search the Store</title>
  <link rel="stylesheet" href="css/styles.css">
</head>
<body>
<h1>Search the Store</h1>
<button>Search</button>
<p id="output"></p>
<script src="js/elements.js"></script>
</body>
</html>

JavaScript:

// button that allows for search
document.querySelector('button').addEventListener('click', function() {
  // first it opens a prompt to type an item and store it in a variable
  search = prompt("Search for a product in our store. Type 'list' to show all of the produce in stock and 'quit' to exit.")
  // sets a variable to print out in the paragraph element with id output
  var outItem = document.getElementById('output')
  // checks if the item is in the array and prints different for each
  // this overwrites what was last searched, so you could add more loop 
  // logic to make it print every search if you want...
  if (inStock.includes(search)) {
    outItem.innerHTML = "We do have " + search + ".";
  } else {
    outItem.innerHTML = "Sorry, we don't have " + search + ". Try going to Costco...";
  }
})

Keep in mind though that this completely defeats the purpose of what we are learning here, which is how to iterate through arrays and find the items inside... Still a nice little workaround for you. If someone can refactor it to print every searched item that would be awesome!!