scott8035
scott8035

Reputation: 461

Why is this checkbox missing the "checked" property?

In a component I'm writing I want to examine the "checked" property of an element. Unfortunately, it appears that the element doesn't contain the "checked" property, at least not the way I set things up.

Here's the JS snippet:

var submenus  = document.querySelectorAll( ".hbm-panel-item-label" );
for ( var label of submenus ) {
  // console.log( "label.for = " + label.getAttribute( "for" ) );

  label.addEventListener( "click", function() {
    var label_for = this.getAttribute( "for" ); 
    // console.log( label_for + " was clicked." );

    var checkboxes = document.querySelectorAll( ".hbm-panel-item-checkbox" );
    for ( var cb of checkboxes ) {
      console.debug( cb );

      if ( cb.getAttribute( "name" ) === label_for ) {
        console.log( label_for + " has attribute 'checked': " + cb.hasAttribute( "checked" ) );
        console.log( label_for + " is " + cb.getAttribute( "checked" ) );  
      }
    }
  });
}

...and here's the result:

Firefox console output

When I open the properties for that element, I do see a checked property with a value of "false":

enter image description here

Apologies in advance, I'm a JS rookie. I get the feeling this is something simple. I also get the feeling that if I used jQuery this would take about three lines of code...

Upvotes: 0

Views: 1443

Answers (1)

Run CMD
Run CMD

Reputation: 3035

A property is in the DOM, an attribute is in the HTML that is parsed into the DOM. The HTML for the checkbox has no attribute 'checked', but the checkbox has a property 'checked'. You'll probably just need to check

cb.checked

instead of looking for the attribute.

Upvotes: 1

Related Questions