/    Sign up×
Community /Pin to ProfileBookmark

Set src inside javascript

I am trying to change a src from img tag inside javascript code. My html code is the following

[CODE]
<div>
<img id = ‘op’ src = ‘2.png’>
</div>
[/CODE]

and script code

[CODE] var image = 1;
var open = ‘images/’+image+’.png’;
console.log(open);
document.getElementById(“op”).src = open;
[/CODE]

I got the message in the condole Cannot set property ‘src’ of null. Ant idea??

to post a comment
JavaScript

2 Comments(s)

Copy linkTweet thisAlerts:
@PadonakOct 24.2013 — maybe you are trying to set the element src attribute before the DOM is loaded?
Copy linkTweet thisAlerts:
@rootOct 25.2013 — Try changing this [code=html]<img id = 'op' src = '2.png'>[/code] to [code=html]<img id='op' src='2.png'>[/code] and [CODE]var image = 1;
var open = 'images/'+image+'.png';
console.log(open);
document.getElementById("op").src = open;[/CODE]
to something like [CODE]window.onload = function(){
var image = 1;
var open = 'images/'+image+'.png';
//console.log(open); <-- try not using this unless you need to.
document.getElementById("op").src = open;
}[/CODE]
and see how you get on.
×

Success!

Help @zenitis spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 6.2,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @meenaratha,
tipped: article
amount: 1000 SATS,

tipper: @meenaratha,
tipped: article
amount: 1000 SATS,

tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,
)...