开发者

Copy class name in javascript

I need a way to copy the class name from one object to another.

For example

<div id="obj1" class"test"></div>
<div id="obj2"></div>

*run code*

<div id="obj1" class"test"></div>
<div id="obj2" class"test"></div>

I'm betting this is a pretty simple quest开发者_运维问答ion, but I'm relatively new to Javascript.

Any help is appreciated.


var obj1 = document.getElementById('obj1'),
    obj2 = document.getElementById('obj2');

obj2.className = obj1.className;

Just make sure this code does not run before the DOM is ready. A simple way to do this is to place this script just before the </body> tag.


document.getElementById("obj2").className = document.getElementById("obj1").className;


<script>
function changeIt(){
     document.getElementById('obj2').className = document.getElementById('obj1').className;

}
changeIt();
</script>


var obj1 = document.getElementById("obj1"),
    obj2 = document.getElementById("obj2");

obj2.className = obj1.className;

Or more generally:

function copyClassName(source, dest) {
    dest.className = source.className;
}

copyClassName(obj1, obj2);
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜