Question

i have an "embed" element

<EMBED id="embed"
 width="100%" height="95%">

and i need to add src to this tag.

<script type="text/javascript">
var source = localStorage.mySrc;
var myEmbed = document.getElementById("embed");
myEmbed.setAttribute("src", source);
//jQuery("#embed").attr("src", localStorage.mySrc);
</script>

When i paste this code to begining i have error "Cannot call method 'setAttribute' of null". when paste to end, its work fine, but the content is already loaded and the script not affect the operation

Was it helpful?

Solution

When i paste this code to begining

Your script appears before the <embed> element.

Your script, therefore, runs before the <embed> element is added to the DOM.

The <embed> element, therefore, does not exist when you try to modify it.

So don't do that.

when paste to end, its work fine, but the content is already loaded and the script not affect the operation

If modifying the element after it exists doesn't work either, then create the entire element using JavaScript.

var myEmbed = document.createElement("embed");
myEmbed.setAttribute("src", source);
document.body.appendChild(myEmbed);

OTHER TIPS

if you add the src before the

<EMBED id="embed" width="100%" height="95%">

is added to the page, it is normal to give you error

uses document.ready , in this manner, the src will be added when the page will be loaded and

<EMBED id="embed" width="100%" height="95%">

will be added to the page

So :

$( document ).ready(function() {

       var source = localStorage.mySrc;
       var myEmbed = document.getElementById("embed");
       myEmbed.setAttribute("src", source);
       //jQuery("#embed").attr("src", localStorage.mySrc);

});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top