简体   繁体   English

如何使用JavaScript在类名中添加前缀

[英]How To Add Prefix in Class's Name Using JavaScript

Hi All I am new in JavaScript. 大家好我是JavaScript新手。 I have one HTML file. 我有一个HTML文件。 And I need to add some word in the class's name. 我需要在课程名称中添加一些单词。 Is there any way to do it using JavaScript? 有没有办法用JavaScript做到这一点?

For Example 例如

<!Doctype HTML>
<html>
    <head>
        <style>
            .heading{color:red;}   
            .text{color:red;}   
        </style>
    </head>
    <body>
        <h1 class="heading">This is heading.</h1>
        <p class="text">This is my text.</p>
    </body>
</html>

In need to add "test-" in the class name in head and body both using JavaScript. 都需要使用JavaScript在头和身体的类名中添加“ test-”。

After using JavaScript function it should look like this. 使用JavaScript函数后,它应如下所示。

<!Doctype HTML>
<html>
    <head>
        <style>
            .test-heading{color:red;}   
            .test-text{color:red;}   
        </style>
    </head>
    <body>
        <h1 class="test-heading">This is heading.</h1>
        <p class="test-text">This is my text.</p>
    </body>
</html>

It would be great help! 这将是极大的帮助! Thanks in advance. 提前致谢。

 //$(".heading").addClass('test-heading').removeClass('heading'); //$(".text").addClass('test-text').removeClass('text') $('.text').attr('class', function() { return $(this).attr('class').replace('text', 'test-text'); }); $('.heading').attr('class', function() { return $(this).attr('class').replace('heading', 'test-heading'); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <html> <head> <style> .heading{color:red;} .text{color:red;} </style> </head> <body> <h1 class="heading">This is heading.</h1> <p class="text">This is my text.</p> </body> </html> 

You can loop Inside the body and add new class. 您可以在主体内部循环并添加新类。

 $("body").children().each(function(index, element) { var oldclass = $(this).attr('class'); var newClass = "test_" + oldclass $(this).removeClass(oldclass).addClass(newClass); }); 
 .test_heading { color: blue; } .test_text { color: blue; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <html> <head> <style> .heading { color: red; } .text { color: red; } </style> </head> <body> <h1 class="heading">This is heading.</h1> <p class="text">This is my text.</p> </body> </html> 

Find all classes of any element, loop through it, add new class and remove existing classes 查找任何元素的所有类,循环遍历,添加新类并删除现有类

var element = "body";
var className= "test-";
var classes = $(element).attr('class').split(" ");
classes.forEach(function(i,obj){
 $(element).addClass(className + i);
 $(element).removeClass(i);
});

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

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