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
Javascript doesn’t have classes, what you are attempting to write is a function.
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.
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.Even if you could assign to this, li elements don’t have a classList method.
There is rarely a good reason to use setAttribute, it is much better to just set the DOM property:
The function can be as suggested by Arend (more or less).