Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why element.setAttribute('checked', true) doesn't work?

I want to do something like this:

elementX.setAttribute('checked', true); // this is input type checkbox
elementY.appendChild(elementX);

It is everything ok with rendering and other things but on the page, the input is not checked. When I look at elements in chrome console I can see:

<input type="checkbox" checked="true">

What should I do?

I've already tried

elementX.setAttribute('checked', true);
elementX.setAttribute('checked', 'true');
elementX.setAttribute('checked', 'checked');

I don't have any errors in the console.

like image 752
xiedzu1503 Avatar asked Mar 14 '26 14:03

xiedzu1503


1 Answers

See MDN:

checked

A Boolean attribute indicating whether or not this checkbox is checked by default (when the page loads). It does not indicate whether this checkbox is currently checked: if the checkbox’s state is changed, this content attribute does not reflect the change. (Only the HTMLInputElement’s checked IDL attribute is updated.).

While setting the checked attribute will show a change in the serialization of the element, it won't actually check the checkbox. For that, you have to invoke the setter, eg

elementX.checked = true;
like image 55
CertainPerformance Avatar answered Mar 17 '26 05:03

CertainPerformance