Change HTML element by ID
Possible Duplicate:
Change an element's CSS class with JavaScript
Found lot of topics about this topic, but none helped me. I have:
<div id="text-6" class="block col-228">
Javascript code should add new class fit, so result should be:
<div id="text-6" class="block col-228 fit">
How to do that with javascript?
Try like this:
var elem = document.getElementById("text-6");
elem.setAttribute("class", elem.getAttribute("class")+" fit");
Important note: You need to be assure,that your DOM Hierarchy
is constructed completely,then try to manipulate DOM Element
s. That is why you need to put DOM
manipulation scripts inside of the window.onload
callback, or if you use jQuery
, then inside of $(document).ready
callback.
您在脚本标记之间放置以下内容。
document.getElementById('text-6').className += " fit";
I'd recommend using jQuery. Then you can just do something like this:
$("#text-6").addClass("fit");
EDIT:
Including the whole jQuery library may be overkill for your situation, but if you're dealing with DOM manipulation a lot, jQuery can simplify things quite a bit. If it's just for this one thing, then some of the other answers provided would be better.
链接地址: http://www.djcxy.com/p/25214.html上一篇: 从阵列中选取随机颜色
下一篇: 通过ID更改HTML元素