document.setAttribute

◇◆丶佛笑我妖孽 提交于 2019-12-10 15:37:21

问题


Can this be used to change CSS? Cant see much on w3 about it. Anyone know anything about it.

If this forum/site isnt the place for asking browser standard questions, can someone point me in the right direction?

Thanks

--Mark


回答1:


Yes, you can use setAttribute to change the CSS of a single DOM element, like so:

document.getElementById("something").setAttribute("style", "color: red;");

However, I believe it's bad practice. You can modify the stylesheet as Marius pointed out by doing:

document.styleSheets[0].cssRules[0].backgroundColor = "#FF0000";

or by manually editing the style attributes of HTML elements, like:

document.body.style.backgroundColor = "#FF0000";

I would recommend looking into jQuery, as it has powerful and easy to use tools for modifying the CSS of DOM elements. It's as simple as:

$("#someID").css({"color": "red", "width": "100px"});



回答2:


Not sure what you mean. If you want to set a CSS value, for example background color, then you have to set that on some element, for example the body:

document.body.style.backgroundColor = "#FF0000";

If you want to change the CSS stylesheet, then you can use the styleSheets object:

document.styleSheets[0].cssRules[0].backgroundColor = "#FF0000";

setAttribute is used to set the attribute of some html element, for example the href in an anchor element:

<a id="link" href="http://www.goolge.com">google</a>



document.getElementById("link").setAttribute("href", "http://www.stackoverflow.com");


来源:https://stackoverflow.com/questions/1225362/document-setattribute

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!