如何使用javascript(No JQ)查找和替换类(How to Find and replace class with javascript (No JQ))

编程入门 行业动态 更新时间:2024-10-27 04:33:50
如何使用javascript(No JQ)查找和替换类(How to Find and replace class with javascript (No JQ))

例如:我有<div class="oneClass twoClass colorRed">Content</div> ,我想找到color*类,并将颜色部分“Red”替换为新值“Blue”或“Yellow”,例如所以现在它将是“ colorBlue ”......

我如何只用Javascript做到这一点?

谢谢!

更新:这不是我的问题: 使用JavaScript更改元素的类

For example: i have <div class="oneClass twoClass colorRed">Content</div> and i want to find the color* class and replace the color part "Red" with the new value "Blue" or "Yellow" for example so it would be "colorBlue" now...

How do i do that with Javascript only ?

Thanks!

Update: This isn't my question: Change an element's class with JavaScript

最满意答案

var node = document.getElementById('someDiv');
node.className = node.className.replace(/color.*/, 'colorBlue'); 
  
/* This css snippet will allow to see 
 * element's classes rendered with the html ;)*/
div:after {
  content: attr(class);
  margin-left: 5px;
  font-style: italic;
  color: gray;
} 
  
<div id="someDiv" class="oneClass twoClass colorRed">Content</div> 
  
 

var node = document.getElementById('someDiv');
node.className = node.className.replace(/color.*/, 'colorBlue'); 
  
/* This css snippet will allow to see 
 * element's classes rendered with the html ;)*/
div:after {
  content: attr(class);
  margin-left: 5px;
  font-style: italic;
  color: gray;
} 
  
<div id="someDiv" class="oneClass twoClass colorRed">Content</div> 
  
 

更多推荐

本文发布于:2023-07-21 09:27:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1208967.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何使用   javascript   JQ   class   replace

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!