user979331
user979331

Reputation: 11861

javascript getElementById.label.style

This is not working for me, and by not working I mean it will not display none on the label....

document.getElementById('clubname').label.style.display = 'none';

What am I doing wrong?

Upvotes: 1

Views: 1761

Answers (2)

RobG
RobG

Reputation: 147403

To decypher what you have:

document.getElementById('clubname')

will attempt to return an element with the id "clubname". If no such element exists, it will return null.

.label

will attempt to access the label property of the object returned above. If that was null, an error will be thrown.

.style

will attempt to access the style property of whatever was returned above. If that value was not an object (or not convertable to an object) like null or undefined then it will throw an error.

.display = 'none';

will either access or assign a display property of the object returned previously and assign it a value of 'none'.

In HTML5, there is a category of labelable elements that have a labels property that references a NodeList of their associated labels. So what the above might do (if it completes without error and accessed a single member of the related labels NodeList, e.g. ...labels[0].style...) is hide the related label. If the element is a child of the label (which they frequently are) it will hide the element too.

But the labels property is not widely implemented yet.

Does that help?

Anyhow, a safer way to do what you want is:

// First attempt to get a reference to the element
var el = document.getElementById('clubname');

// If the above returned an element, and it has a labels property
// and that property has at least one member
if (el && el.labels && el.labels[0]) {

    // Safe to assume el.labels[0] is a DOM element, so
    // mess with its style object
    el.labels[0].style.display = 'none';

Upvotes: 1

Alohci
Alohci

Reputation: 82986

Labelable elements can have multiple labels, so the elements have a labels property not a label property.

But I don't know what the level of browser support is for this property currently.

Upvotes: 1

Related Questions