Changing the innerHTML of a tag

Asked

Viewed 457 times

1

I’m in a little trouble when I’m going to change a property of any tag using Javascript or browser says:

Uncaught Typeerror: Cannot set Property 'src' of null

But I tested it on Jsfiddle and it worked correctly with the same parameters!

Code:

function get(idOf) {
    return document.getElementById(idOf);
}

function loadData(id, videoDATA) {
    get(id).src = "https://www.youtube.com/embed/" + videoDATA;
}

window.onload = function () {
    get('404').innerHtml = '<iframe src="" width="500px" height="400px" frameborder="0" id="frame0"></iframe>';
    loadData('frame0', 'kdWAmMRmELg');
}

<div id="404">...</div> is a DIV I put in case the videoDATA were not loaded.

  • Jsfiddle test: http://jsfiddle.net/4tmjjLzk/

  • No Jsfiddle error you sent.

  • what would be <head> in wrap! so jsfiddle did not interpret the error!

  • @Nathan1302 No wrap - in <head>, in Portuguese: Em <head>, means that the script will be placed inside the <head> in the fiddle :)

2 answers

2

This error occurs because you are trying to change the src an element that was not found on the page. And it was not found because the line that trial create it is wrong. You need to use innerHTML instead of innerHtml:

window.onload = function () {
    get('404').innerHTML = '<iframe src="" width="500px" height="400px" frameborder="0" id="frame0"></iframe>';
    loadData('frame0', 'kdWAmMRmELg');
}

http://jsbin.com/hipogiwali/1/edit

  • +1 for the answer. Off-topic: Stacksnippet’s "Sandbox" does not include <iframe> to post a functional example?

  • I don’t know, I used jsbin precisely to avoid cross-Omain access problems. Jsfiddle would complain.

-1

Barter window.onload for document.onready.

Probably in Jsfiddle not error because the Javascripts that are loaded are at the end of the HTML where sure they are ready.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.