6种方法改变div的id值(使用JQuery或JS)
作者:admin 时间:2018-9-28 15:3:22 浏览:10138div的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();');
这里要用到setAttribute
方法,这个也是改变div id的第6种方法。