0

So I made a list in html and gave every option a value of numbers (0,1,2,...) and gave all the options the same class 'op' and then I want to save this values in an array in javascript but my code doesn't seem to work.

output should be [0,1,2,3,...] instead nothing happens

    let valuesofnames = [];
    let valuesfromhtml = document.getElementsByClassName('op').value;
    valuesofnames.push(valuesfromhtml);
    console.log(valuesofnames)
Marco Maher
  • 351
  • 1
  • 9
  • As far as I know one cannot simply push an array into an array. You'll probably want to run array.sliice(); or in your case const valuesofnames = valuesfromhtml.slice(); – FujiRoyale May 14 '20 at 23:01
  • `getElementsByClassName` returns a `NodeList`. You need to loop over the list. – Barmar May 14 '20 at 23:11
  • ```let valuesfromhtml = document.getElementsByClassName('op'); const valuesofnames = Object.keys(valuesfromhtml).map((key) => valuesfromhtml[key].value); console.log(valuesofnames)```. – Zain Zafar May 14 '20 at 23:21
  • can you explain your code more specifically please zain zafar – Marco Maher May 14 '20 at 23:27
  • why does it return a nodelist and why doesn't it store the values @Barmar – Marco Maher May 14 '20 at 23:31
  • What should it return instead? You asked for all the elements with that class, not just a single element. Each element in the collection can have a different value, so what do you expect `.value` to return? – Barmar May 14 '20 at 23:33
  • Doesn't the linked question explain this? – Barmar May 14 '20 at 23:33
  • I expect it to return the values of all classes having the same class name – Marco Maher May 14 '20 at 23:41
  • I changed my code according to the question you directed me to and here is what i made `let valuesfromhtml = document.getElementsByClassName('op').value; function test(value){ for (i=0 ; i < valuesfromhtml ; i++){ let valuesofnames = []; valuesofnames.push(valuesfromhtml); console.log(valuesofnames) } }` – Marco Maher May 14 '20 at 23:42
  • here i tried to make a loop and save the value in the order of how the loop go and yet it doesn't do anything – Marco Maher May 14 '20 at 23:45
  • I just wanted to thank you for giving me your time to answer my questions. – Marco Maher May 14 '20 at 23:46

0 Answers0