Q:

Using variable as value in object assignment - JavaScript

If we have the following code
<ul>
    <li id='car'>ok</li>
    <li id='color'>dd</li>
</ul>

I can apply a name attribute directly with the following code
car.setAttribute('name', 'bmw');

However what if I want to use a variable in the place of car.
var z = 'car';
z.setAttribute('name', 'bmw');

This doesn't work. Or harder still, what about using both?
var z = 'r';
ca + z.setAttribute('name', 'bmw');

Also doesn't work.
Is this possible?

A:

It looks like you're relying on the automatic globals that browsers create for elements that have ids (which I don't recommend). If so, you can do it by using the window object:
var c = 'car';
window[c].setAttribute('name', 'car');

var ca = 'ca';
window[ca + 'r'].setAttribute('name', 'car');

All global variables are properties of the global object, which you can access as window on browsers. (In fact, window itself is a property of the global object, which it uses to refer to itself.) In JavaScript, you can refer to properties on objects using dot notation and a literal name (obj.foo), or bracketed notation and a string name (obj["foo"]). In the latter case, the string can be the result of any expression, including a variable lookup.
I don't recommend relying on automatic globals, though, the global namespace is really crowded and other things (declared variables, functions) can shadow the elements. Use getElementById instead:
var c = 'car';
document.getElementById(c).setAttribute('name', 'car');

var ca = 'ca';
document.getElementById(ca + 'r').setAttribute('name', 'car');

Side note: name isn't a valid attribute for li elements.

