Reputation: 1145
This is my code:
var chk="checked";
document.getElementById("chk").chk=true;
where I used variable to set attribute in the second line.
but this is not working with no error.
Please help me to find this.
Upvotes: 0
Views: 808
Reputation: 35950
You might want:
document.getElementById("chk").setAttribute(chk, true);
which will set it as HTML attribute (not the object property - for that you'd use []
brackets). This is what you're probably looking for because you're operating on an HTMLElememnt.
To clarify:
<div>
into that: <div checked="true">
(assuming the element under question is a div)[]
- use for plain JS objects. In that case the name 'property' is rather used, not 'attribute'Also note that if the element is <input>
, both approaches will work. That's because HTMLInputElement contains the 'checked' attribute. See HTMLInputElement MDN page for details.
Upvotes: 2
Reputation: 172408
Try this:
document.getElementById("chk")[chk] = true;
This one sets the property
or use the .setAttribute property
document.getElementById("chk").setAttribute(chk, true);
This will set the attribute. If you are using it on HTML elements then this one is a better pick for you as this will set the HTML attribute.
Upvotes: 1
Reputation: 1068
chk is a javascript variable in your case. When you getElementById, it refers to the HTML document and the tags in it. Example,
<input id=appleId type="radio" name="fruit" value="Apple" />
In JS, you can then say,
document.getElementById("appleId").checked = true;
Refer to How can I check whether a radio button is selected with JavaScript?
Upvotes: 0
Reputation: 2330
Use like this.
document.getElementById("chk").setAttribute(chk, true);
Upvotes: 1
Reputation: 95489
You can add variables to any JavaScript object which is why the code will run without an error, but -- as you've observed -- it won't have any side effects if the property is not a predefined, semantically meaningful one. For that, you should read some documentation for the given element. For the checkbox element, the name of the property you are looking for is checked
. (Note that using the dot syntax treats the text to the right as the name of the property, it does not evaluate it, first. For dynamic evaluation of the property name, use the []
syntax for normal objects and setAttribute
for HTML attributes).
Upvotes: 0