phurst-so
phurst-so

Reputation: 386

Storing for loop result to push into HTML

EDIT: Solved. After the helpful people here helped me solve this I realised this issue was to do with my getElementsByClassName selector. Sorry if the title is misleading. The original question is below.

I am getting the expected results from this function's for loop, but I can't get them to print to the HTML.

Could anybody help point out what I'm missing? A point in the right direction would do, I can do some legwork myself.

Any advice is much appreciated.

HTML:

<input type="text" name="searchString" class="searchString">

<span class="longestWordInput"></span>
<span class="longestWordCountInput"></span>

<button class="generate">Generate</button>

JavaScript:

function longestWordFunc() {
  var stringSplit = document.querySelector(".searchString").value.split(" ");

  let longestWordCount = 0;
  let longestWord = "";

  for(var i = 0; i < stringSplit.length; i++) {
    if(stringSplit[i].length > longestWordCount) {

      longestWordCount = stringSplit[i].length; 
      longestWord = stringSplit[i]
    }
  }

  //Logging expected result
  console.log(longestWordCount)
  console.log(longestWord)

  //Print to HTML not working
  document.getElementsByClassName("longestWordInput").innerHTML = longestWord;
  document.getElementsByClassName("longestWordCountInput").innerHTML = longestWordCount;
};

document.querySelector(".generate").addEventListener("click", longestWordFunc);

Upvotes: 2

Views: 30

Answers (2)

not a number
not a number

Reputation: 256

The problem is that getElementsByClassName() returns a NodeList (an array-like structure containing all elements with the specified class name) instead of a single element.

You can access your single span element like this

document.getElementsByClassName("longestWordInput")[0].innerHTML = longestWord;

or you could use querySelector() instead

document.querySelector(".longestWordInput").innerHTML = longestWord;

Upvotes: 1

magegaga.com
magegaga.com

Reputation: 500

Hi I believe you need to use getElementsByClassName like the below

document.getElementsByClassName("longestWordInput")[0].innerHTML = longestWord;
document.getElementsByClassName("longestWordCountInput")[0].innerHTML = longestWordCount;

Upvotes: 1

Related Questions