开发者

Changing an image via Javascript?

Quick question regarding Javascript. I'm working on a Safari Extension for paring down the Google Search page, and I'd like to change the Google logo to a custom image. My plan is to have an injected .js script to put in the extension.

So far, I've tried this:

document.getElementById('img#hplogo').innerHTML = 开发者_运维问答
"<img alt="Google" height="95" id="hplogo" src="logo3w.png" width="275" 
style="padding-top:136px" onload="window.lol&amp;&amp;lol()">"

For some clarification, the logo image is under the ID on the Google homepage as "hplogo" or according to Safari Web Inspector, "img#hplogo". I want to replace the src, obviously, with my own logo3w.png that will be located in the root of the extension folder (thus, AFAIK, no advanced directory is needed).

If I could be pointed in the right direction command-wise, that'd be really helpful, but really any and all help is appreciated. Thanks!


You want to do:

document.getElementById("hplogo").src = "logo3w.png";

Note that the "img#hplogo" is not saying that the id of the img element is "img#hplogo", it is saying that you are looking at an "img" element whose id is "hplogo". So when using document.getElementById() you only need to pass "hplogo". In CSS you might say:

img #hplogo {
    display: none;  //or whatever
}
#hplogo {
    display: none;  //or whatever
}

And similarly with something like jQuery that supports CSS-style element selectors you might say:

var image = $("#hpLogo");
var theSameImage = $("img #hplogo");

But for document.getElementById() all you need to pass (and all you can pass) is "hplogo".


You may want to change the src attribute of the image:

document.getElementById('img#hplogo').src = 'path/to/your/image.jpg'


Changing the "innerHTML" property changes the inner HTML, not the element itself. The thing you want to do is find the element and change it's "src" property.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜