首页 > 运营 > 帮助中心 > 正文

改变div的id值的6种方法(使用JQuery或JS)

2020-01-28 10:26:01
字体:
来源:转载
供稿:网友

div的id是可以动态改变的,我们可以通过JQuery或JS来实现。

使用JQuery或JS改变div id

使用JQuery改变div id

通过使用JQuery的attr()方法,有三种方式可以实现改变div的id值。

1)byTagName

$('div').attr('id','id_new');

2)byId

$('#div_id').attr('id','id_new');

3)byClass

$('.div_class').attr('id','id_new');

不过在实际应用中,byId是最保险的写法,任何时候都可以用。而byTagName仅当网页只有一个div时可以使用,byClass则不能在网页里出现多个div使用同一个class。

使用JS改变div id

通过使用JS,有两种方式可以实现改变div的id值。

1)byTagName

document.getElementsByTagName("div").id = 'id_new';

2)byId

document.getElementById("div_id").id = 'id_new';

不过在实际应用中,byId是最保险的写法,任何时候都可以用。而byTagName仅当网页只有一个div时可以使用。

完整范例

1、example-jquery.html

<html><head><title>使用jQuery改变div id</title></html><body><div id="div_id1"></div><!--引用jquery cdn--><script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script><script> $(document).ready(function(){   $('#div_id1).attr('id','div_id2'); });</script></body></html>

2、example-js.html

<html><head><title>使用js改变div id</title></html><body><div id="div_id1"></div><script> document.getElementById("div_id1").id = 'div_id2';</script></body></html>

不仅仅能改变id

不仅能改变id,也能改变class、鼠标事件或其他任何属性。

document.getElementById('demo').setAttribute('id','demoSecond');document.getElementById('demo').setAttribute('class','new');document.getElementById('demo').setAttribute('onclick','doThis();');


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表