Home > front end >  Why does my function return undefined, especially the .split()parts?
Why does my function return undefined, especially the .split()parts?

Time:01-08

So in essence I get the value of input, then try to divide into into different tags via the comma with this

     var noteTags = document.getElementsByClassName("noteTag").value;
          Tag = noteTags.split(",");

But in console, the split(",") is undefined

CodePudding user response:

There are two issues,

  1. getElementsByClassName returns an array-like collection of elements (a NodeList).
  2. And instead of value it should be innerText.

Try like below

 var noteTags = document.getElementsByClassName("noteTag")[0].innerText;
      Tag = noteTags.split(",");

CodePudding user response:

You are using the split() method on an array. You are also trying to access the value property, whereby you should probably use innerText.

CodePudding user response:

You can use querySelector then you dont need using a key[0] to select the element.

const noteTags = document.querySelector("#noteTag");
console.log(noteTags)
Tag = noteTags.innerHTML.split(",");
console.log(Tag)
<div id="noteTag">en,jp,fr</div>

  •  Tags:  
  • Related