简体   繁体   中英

Why is javascript not recognising an ID tag I've created?

I've given the element "characterImage" an ID tag but javascript doesn't seem to be recognising that I've given it an ID even though I used (for example) element.id = "desiredID" .

The firefox webConsole just keeps returning document.getElementById(..) is null" even though I've definetely set an ID and put it within the curly braces

I've tried both the setAttributeAs() method and element.id = "desiredID"

{
let characterImage = document.createElement("IMG");
characterImage.id = "characterImg";
characterImage.src = "Story Game Photos";
characterImage.style.height = "250px";
characterImage.style.height = "250px";
}

function henryFunction(){
document.getElementById("characterImg").src = "Story Game photos/h.jpg";
document.getElementById("characterImg").appendChild(divCharacterImage);
}

error message I'm receiving:

TypeError: document.getElementById(...) is null

Expected result: for javascript to recognise the ID and put my desired picture in its desired place

You have to append the image element to an element in the document. When the element is present in the DOM then you can find it using the id , using

document.getElementById()

Add the line

 document.querySelector("body").appendChild(characterImage)

to append the element to the body tag

 function a(){ let characterImage = document.createElement("IMG"); characterImage.id = "characterImg"; characterImage.src = "Story Game Photos"; characterImage.style.height = "250px"; characterImage.style.height = "250px"; document.querySelector("body").appendChild(characterImage) henryFunction(); } function henryFunction(){ document.getElementById("characterImg").src = "https://placekitten.com/g/200/300"; } a(); 
 <html> <body> </body> </html> 

Before accessing it from dom you have to append it to the parent. So use .appendChild(divCharacterImage); befor running henryFunction(); in your main function.

function a(){
    let characterImage = document.createElement("IMG");
    characterImage.id = "characterImg";
    characterImage.src = "Story Game Photos";
    characterImage.style.height = "250px";
    characterImage.style.height = "250px";
    document.querySelector("body").appendChild(characterImage)
    document.getElementById("characterImg").appendChild(divCharacterImage);
    henryFunction();
}

function henryFunction(){
    document.getElementById("characterImg").src = "Story Game photos/h.jpg";
}

Just check this update to your code.

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