It looks like you're relying on the automatic globals that browsers create for elements that have id
s (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.