最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

php - adding class to div element using javascript - Stack Overflow

programmeradmin0浏览0评论

im really new to js, and im currently making a webiste. 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. 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. 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>

im really new to js, and im currently making a webiste. 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. 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. 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>
Share Improve this question asked Mar 29, 2022 at 8:10 KAZKAZ 311 gold badge1 silver badge2 bronze badges 1
  • Try element.classList.add("active");. Get rid of lines: var id = element.id; and getElementsByClassName(id).classList.add("active");. – Robert Commented Mar 29, 2022 at 8:16
Add a ment  | 

4 Answers 4

Reset to default 2

you can use this code:

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

ids of the elements should be unique , search your element by id and then remove or add the desired class name

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

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

you can do it like that:

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

In jQuery

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

instead of addClass you can toggleClass for removing and adding class

发布评论

评论列表(0)

  1. 暂无评论