This is my code :

(a=document).getElementsByTagName('body')[0].appendChild(a.createElement('div').style.cssText="someCssStyle");

it doesn't work ! but when i write only this :

(a=document).getElementsByTagName('body')[0].appendChild(a.createElement('div'));

It works, so why can't I add the div element with a specific style? What's wrong with my work? I want to add a div element with a specific style just from the URL implantation on chrome using :

javascript://all of my code goes here

So it must be short.

有帮助吗?

解决方案

a.createElement('div').style.cssText="someCssStyle"

This will return "someCssStyle" which will be given as argument to (a=document).getElementsByTagName('body')[0].appendChild( function. So the div is never added. Can you see the problem here ?

You have to create the div, style it and then add it to the body. Like this

var div = document.createElement("div");
div.style.cssText = "someCssStyle";

document.body.appendChild(div);

其他提示

The reason it doesn't work is that here:

...appendChild(a.createElement('div').style.cssText="someCssStyle")

you're passing a string ("someCssStyle") into appendChild, rather than the element reference. The result of an assignment in JavaScript is the right-hand value.

I don't recommend it, but you can use the comma operator to do this:

(a=document).getElementsByTagName('body')[0].appendChild(d=a.createElement('div'),d.style.cssText="someCssStyle",d);

Note that your code, and the above, both fall prey to The Horror of Implicit Globals.

Or more reasonably, a function:

(function(){var a=document,d=document.createElement('div');d.style.cssText="someCssStyle";a.getElementsByTagName('body')[0].appendChild(d)})();

...which amongst other things doesn't fall prey to THoIG.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top