-2

My objective is to create a input and append a value with javascript

This is my code:

count = [1,1,1,1,1,1,1,1];
text = document.createElement('input');
text.className='text1';
node = document.getElementsByClassName('text1').value ='Enter';
document.body.append(text);
mega6382
  • 9,211
  • 17
  • 48
  • 69
cord
  • 75
  • 1
  • 2
  • 8

3 Answers3

1

You don't need to use getElementsByClassName since you already have the new input in your text variable.

var count = [1,1,1,1,1,1,1,1];
var text = document.createElement('input');
text.className='text1';
text.value ='Enter';
document.body.append(text);
Nick
  • 16,066
  • 3
  • 16
  • 32
  • He probably knows this already, since he adds `text` to the body already – Icepickle Oct 27 '17 at 13:28
  • @Icepickle He probably hardly knows, because why else would he use `getElementsByClassName` when it is not needed, does not work, and leads to a question on SO. – Peter B Oct 27 '17 at 13:31
  • @PeterB If that is the question, then it should be closed at a duplicate, but I really don't know what the op means with appending the value to something, so I rather don't think the question should be answered at all – Icepickle Oct 27 '17 at 13:34
1

getElementsByClassName does not return a single element, and even if it did: The element you are trying to modify hasn't been added to the document you are searching!

You already have the element in the text variable. Use that:

text.value = "Enter";
mega6382
  • 9,211
  • 17
  • 48
  • 69
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
0

You cannot use getElementsByClassName because, the lement is not appended to the document yet.

    text = document.createElement('input');
    text.className='text1';
    text.value ='Enter';
    document.body.append(text);

Alternatively You can use getElementsByClassName but only after you have appended the element to the document. But as getElementsByClassName selects multiple elements you have to define an index:

    text = document.createElement('input');
    text.className='text1';
    document.body.append(text);
    document.getElementsByClassName('text1')[0].value = 'Enter';

Instead of class you can use an id:

    text = document.createElement('input');
    text.id='text1';
    document.body.append(text);
    document.getElementById('text1').value = 'Enter';
mega6382
  • 9,211
  • 17
  • 48
  • 69