Reputation: 2996
I want to make a class that creates an element with a few properties added on to it. So far this is what my code looks like:
function CreateItem(n,u) {
this=document.createElement('li');
this.classList.add('ui-state-default');
this.setAttribute('value',u);
this.innerHTML=n;
}
It doesn't work. I keep getting an error:
ReferenceError
arguments: Array[0]
message: "_"
stack: "_"
type: "invalid_lhs_in_assignment"
__proto__: Error
What I want is it to return an li
element like this:
<li value="u">n</li>
If it helps here's what I'm using:
Google Chrome: 13.0.782.1 (Official Build 87465) dev
OS: Linux
WebKit: 535.1 (trunk@87771)
JavaScript: V8 3.4.0.1
Flash: 10.3 r181
User Agent: Mozilla/5.0 (X11; Linux i686) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/13.0.782.1 Safari/535.1
and debugging with Chrome Dev Tools
Upvotes: 0
Views: 241
Reputation: 147343
I want to make a class that creates an element with a few properties added on to it. So far this is what my code looks like:
Javascript doesn't have classes, what you are attempting to write is a function.
> function CreateItem(n,u) {
By convention, function names starting with a capital letter are constructors and should be called with new. You don't show how the function is called, but I expect it is with new.
> this=document.createElement('li');
You can't assign a value to this (hence why the error message says invalid_lhs_in_assignment
)), it is set when the execution context is entered and can't be changed.
> this.classList.add('ui-state-default');
Even if you could assign to this, li elements don't have a classList method.
> this.setAttribute('value',u);
There is rarely a good reason to use setAttribute, it is much better to just set the DOM property:
el.value = u;
The function can be as suggested by Arend (more or less).
Upvotes: 2
Reputation: 707
Given this syntax, the 'this' keyword probably refers to the global 'window' object. If you are calling the function with the 'new' keyword, the function is being called as a constructor, and you are trying to overwrite the object that it is trying to construct. Try this istead:
function CreateItem(n,u) {
var li=document.createElement('li');
li.classList.add('ui-state-default');
li.setAttribute('value',u);
li.innerHTML=n;
return li;
}
Upvotes: 0
Reputation: 3761
I think you can't write to "this" But this will work:
function CreateItem(n,u) {
var el =document.createElement('li');
el.classList.add('ui-state-default');
el.setAttribute('value',u);
el.innerHTML=n;
return el;
}
Upvotes: 4