开发者

changing content of p element using innerHTML

I have the following script:

var before = document.getElementById('before');    
if (switchElement.value == 'single'){
    for (var i=0; i < before.length; i++) {
        if (before[i].id == "before_label") {
            before[i].innerHTML = 'Image';
            break;
        }
    }
    after.style.display = 'none';   
} 

and the HTML looks like:

<div id="before">
    <p id="before_label"> Before Image: </p>
    <input type="file" name="before开发者_运维百科"  size="40">
    <input type="hidden" name="MAX_FILE_SIZE" value="10000000">
</div>

Was wondering why it didn't work and change the inner html to change?


To access the innerHTML of before_label, just access it directly:

document.getElementById('before_label').innerHTML = 'Image';


getElementById only returns one element. You need to acces the child objects via childNodes.

Try this:

var before = document.getElementById('before').childNodes;    
if (switchElement.value == 'single'){
    for (var i=0; i < before.length; i++) {
        if (before[i].id == "before_label") {
            before[i].innerHTML = 'Image';
            break;
        }
    }
    after.style.display = 'none';   
} 


Why the for loop? Just get the element by its id:

var before_label = document.getElementById('before_label');
if (switchElement.value == 'single') {
    before_label.innerHTML = 'Image';
    after.style.display = 'none';
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜