3

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 Edit: Sorry I forgot to mention that the noteTag element is input, does this change how the code works in any way?

  • Does this answer your question? [getElementsByClassName doesn't work, but getElementById does?](https://stackoverflow.com/questions/39178138/getelementsbyclassname-doesnt-work-but-getelementbyid-does) – steven7mwesigwa Jan 07 '22 at 15:14
  • 2
    Does this answer your question? [What do querySelectorAll and getElementsBy\* methods return?](https://stackoverflow.com/questions/10693845/what-do-queryselectorall-and-getelementsby-methods-return) – CherryDT Jan 07 '22 at 15:16
  • 1
    "But in console, the split(",") is 'undefined'" - no it's not, please read the message again more thoroughly. It says probably "Cannot read properties of undefined (reading 'split')". So it says, the property "split" of an undefined value cannot be read. So, that means, **`noteTags` must have been `undefined`** (not the result of `split`) so that it tried to do `undefined.split(",")`! And why is that? Because you accessed the `value` property of whatever `getElementsByClassName` returned and it was `undefined`, so you did something wrong there. (As noted, a `NodeList` doesn't have a `value`.) – CherryDT Jan 07 '22 at 15:17
  • Wow I never considered that the value .split(",") was used with was undefined, that would have been a lot easier to resolve, thanks – Liam Osvaldo Jan 07 '22 at 15:35
  • Wat exactly does getElementById('').value actually return, a string or some other data type? – Liam Osvaldo Jan 07 '22 at 15:39

3 Answers3

3

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(",");
CherryDT
  • 25,571
  • 5
  • 49
  • 74
Amila Senadheera
  • 12,229
  • 15
  • 27
  • 43
1

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

Jaka-k
  • 11
  • 2
1

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>
Maik Lowrey
  • 15,957
  • 6
  • 40
  • 79