3

I'm using js to change the contents of a div that contents inputs i want to use them with Ajax , I've used Firefox scratchpad to debug this function:

function show(id){
var div = document.getElementById('com');
div.innerHTML = '';
var input1 = document.createElement('input')
            .createAttribute('type').setAttribute('type', 'hidden')
            .createAttribute('value').setAttribute('value',id )
            .setAttribute('name','id' );
var input2 = document.createElement('input')
             .createAttribute('type').setAttribute('type', 'input')
             .createAttribute('name').setAttribute('name', 'com');
var btn = document.createElement('button')
          .createAttribute('onClick').setAttribute('onClick', 'post()');
btn.innerHTML = 'Comment';
div.appendChild(input1).appendChild(input2).appendChild(btn);
}

and what i got is this:

/*
Exception: document.createElement(...).createAttribute is not a function
@Scratchpad/2:2
*/

I understood nothing, any ideas?

Majed DH
  • 1,251
  • 18
  • 35

2 Answers2

7

I believe .createAttribute() belongs to document, not to individual elements, so that would explain that error: .createElement() returns an element, and that element has no function .createAttribute().

But you don't need to use .createAttribute() before calling .setAttribute(), because the latter will create element attributes if they don't already exist. However, I think .setAttribute() returns undefined so you can't really chain it. Try doing it one step at a time:

var input1 = document.createElement('input');
input1.setAttribute('type', 'hidden');
input1.setAttribute('value',id );
input1.setAttribute('name','id' );
// etc.
nnnnnn
  • 147,572
  • 30
  • 200
  • 241
3

Basically, the exception says that there is no function called "createAttribute". And that is correct:

.createAttribute() is a function of document: https://developer.mozilla.org/en-US/docs/DOM/document#Methods

So the functions cannot be chained like you try to do it. You have to call them individually. And anyway, "createAttribute" should not be used anymore (see Using createAttribute vs. just setting the attribute directly?).

function show(id){
    var div = document.getElementById('com');
    div.innerHTML = '';

    var input1 = document.createElement('input');
    input1.setAttribute('type', 'hidden');
    input1.setAttribute('value',id );
    input1.setAttribute('name','id' );

    var input2 = document.createElement('input');
    input2.setAttribute('type', 'input');
    input2.setAttribute('name', 'com');

    var btn = document.createElement('button');
    btn.setAttribute('onClick', 'post()');
    btn.innerHTML = 'Comment';

    div.appendChild(input1).appendChild(input2).appendChild(btn);
}
Community
  • 1
  • 1
Ignitor
  • 2,907
  • 33
  • 50