简体   繁体   English

将类添加到其ID与另一个元素的类匹配的元素

[英]Add class to element whose id matches the class of another element

I want to take the second class of an element, and then add a class to the element that has that ID. 我想获取元素的第二个类,然后将一个类添加到具有该ID的元素中。 In Chrome, Firefox, etc. it works perfectly but in IE11 it does not. 在Chrome,Firefox等中,它可以完美运行,但在IE11中则不能。 Do you know why? 你知道为什么吗? Help me please 请帮帮我

for (var i = 0; i < $('#example .item').length; i++) {
  var class_svg = document.getElementsByClassName("item")[i].className.split(' ')[1];
  var $elem = document.getElementById(class_svg);  
  $elem.classList.add("show");
}

According to the docs classList is only partially supported before Edge. 根据文档,在Edge之前仅部分支持classList Use className instead like: 使用className代替:

$elem.className += ' show';

edit: thanks for the hint @Sterling Archer 编辑:感谢提示@Sterling Archer

Creating a basic example using an SVG element (which I assume you have based on your example code) and looking at it in IE11 and Edge, you can see that the className property is a [object SVGAnimatedString] . 使用SVG元素创建一个基本示例(假定您已经基于示例代码了),然后在IE11和Edge中进行查看,您可以看到className属性是[object SVGAnimatedString] That is some special object for SVG elements, instead of dealing with that special object, lets just deal with the attribute itself using getAttribute . 这是SVG元素的一些特殊对象,而不是处理该特殊对象,而只需使用getAttribute处理属性本身即可。 Here is the code that works in most all browsers: 以下是适用于大多数浏览器的代码:

for (var i = 0; i < $('#example .item').length; i++) {
  var class_svg = document.getElementsByClassName("item")[i].getAttribute("class").split(' ')[1];
  var $elem = document.getElementById(class_svg); 
  var classList = $elem.getAttribute("class");
  classList += " show";
  $elem.setAttribute("class",classList);
}

Hope that works for you. 希望对您有用。

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

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