简体   繁体   English

使用 javascript 将 class 添加到 div 元素

[英]adding class to div element using javascript

im really new to js, and im currently making a webiste.我真的是 js 的新手,我目前正在制作一个网站。 Because i have a repeated html code for the header and footer of the wepage, i used php to call the html file rather than repeating the same code.因为我有 header 和页面页脚的重复 html 代码,所以我使用 php 调用 html 文件,而不是重复相同的代码。 On the other hand,i wanted the current active page to have a different color, therefor i am using javascript to get the name of the class and add the class active to make a exeption in css. getting the id seems to be working, but i cant find the class active being add.另一方面,我希望当前活动页面具有不同的颜色,因此我使用 javascript 获取 class 的名称并添加 class active以在 css 中进行异常处理。获取 ID 似乎有效,但是我找不到正在添加的 class active why is this?为什么是这样?

<p class="activepage" id="felt">aegearg<p>    
<script>
      var element = document.getElementsByClassName("activepage")[0];
      var id = element.id;
      getElementsByClassName(id).classList.add("active");
    </script>

ids of the elements should be unique, search your element by id and then remove or add the desired class name元素的 id 应该是唯一的,通过 id 搜索你的元素,然后删除或添加所需的 class 名称

document.getElementById("MyElement").classList.add('MyClass');

document.getElementById("MyElement").classList.remove('MyClass');

you can use this code:您可以使用此代码:

document.getElementById("IdElement").classList.add("ClassNameAdd");

you can do it like that:你可以这样做:

const element = document.QuerySelector("#activepage");
element.ClassList.add("active");

In jQuery jQuery

$('#activepage').addClass('active');

instead of addClass you can toggleClass for removing and adding class而不是 addClass 你可以 toggleClass 删除和添加 class

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM