简体   繁体   中英

javascript cannot read property 'style' of null

This function is supposed to hide the patient note and show the next note (if they have another note)

function nextNote(idno){
    document.getElementById(idno).style.display = 'none';
    var idno2 = parseInt(idno)+1;
    document.getElementById(idno2.toString()).style.display = 'inline';
    document.getElementById('prevNote').label = parseInt(document.getElementById('prevNote').label) + 1;
    document.getElementById('nextNote').label = parseInt(document.getElementById('nextNote').label) + 1;

Uncaught TypeError: Cannot read property 'style' of null at "document.getElementById(idno).style.display = 'none';

The element in question <li class="notes" label="1052" style="display: inline;" id="1">On: 5/17/2004 A real good Patient test</li> <li class="notes" label="1052" style="display: inline;" id="1">On: 5/17/2004 A real good Patient test</li>

nextNote is being called by: <input type="button" id="nextNote" class="notesbottombutton" value=">" label="1" onclick="nextNote(this.label);" /> <input type="button" id="nextNote" class="notesbottombutton" value=">" label="1" onclick="nextNote(this.label);" />

If I use the Chrome javascript console document.getElementById(1).style.display; I get: "inline"

Note I will add checks to the function after I get it work such as if(document.getElementById(idno2.toString()) so that it doesn't do anything if there are no more notes to display, I am just trying to get the basic functionality first

Maybe the problem is your click handler:

nextNote(this.label);

label is not a property of HTML inputs. It's not even a valid attribute. To set the caption of an input with type="button" , you should use its value attribute and use this.value to access it.

If you're just using this attribute to attach data to the element and want to access the attribute, you should do it like this:

nextNote(this.getAttribute('label'));

But I'd recommended that you use a data- prefixed attribute instead, the standard way to attach data in HTML 5 (it's also backwards compatible):

<input data-label="foo" />

nextNote(this.getAttribute('data-label'));

this.label refers to the label property on the element, but you are setting an attribute called label. Change your onclick to:

onclick="nextNote(this.getAttribute('label'));"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM