js或者jquery 如何给元素增加ID

js或者jquery 如何给元素增加ID,第1张

需要准备的材料分别有:电脑、html编辑器浏览器

1、首先,打开html编辑器,新建html文件,例如:index.html,编写问题基础代码。

2、在index.html中的<script>标签,输入js代码:$('li a').each(function (i, e) {$(this).attr('id', 'id1_' + i)})。

3、浏览器运行index.html页面,此时发现元素被js按照需求新增了id属性。

因为是用class,没有id,所以只能假设只有一个div是这个class来做:

<!DOCTYPE html>

<html>

<head>

<meta charset="UTF-8">

</head>

<body>

<div class="div-test">123</div>

<script>

document.getElementsByClassName("div-test")[0].style.backgroundColor = "red"

</script>

</body>

</html>

望采纳,谢谢

引用楼上的document.getElementById("01").className="aa"//aa是class名称

如果用jquery的方法,就更简单一点$("#01").attr("class","aa")


欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/bake/11568993.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2023-05-17
下一篇2023-05-17

发表评论

登录后才能评论

评论列表(0条)

    保存