在JavaScript中获取CSS类名

时间:2021-05-16 14:28:41

I am facing a problem to get the class name from a string in JavaScript.

我在使用JavaScript中的字符串中获取类名时遇到问题。

For example:

var ddd="<p class='Box_title'>Heading text here...</p>";

Now from that I want to get p tag's class name.

从那以后我想得到p标签的类名。

4 个解决方案

#1


13  

Browsers are good in HTML parsing:

浏览器很适合HTML解析:

//setup
var tmp = document.createElement('div');
tmp.innerHTML = ddd;

// get the class
var class_name = tmp.children[0].className;

#2


0  

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> 
 <html>
   <head>
     <title>Ejemplo</title>
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
       <script type="text/javascript">
           $(document).ready(function() {
                var ddd="<p class='Box_title'>Heading text here...</p>";
                $('.container').append(ddd);
                alert($('.container').children(':first-child').attr("class"));
        });
       </script>
   </head>
   <body>
     <div class="container">
    </div>
   </body>
 </html>

#3


-2  

   var RegExp = /class='(.+)'/;
   var result = RegExp.exec("<p class='Box_title'>Heading text here...</p>");

this will return an array with class name as one of it's elements

这将返回一个类名作为其中一个元素的数组

#4


-2  

var d = "<p class='Box_title'>Heading text here...</p>";
var cls = d.match(/class\=\'(.*)\'/);
alert(cls[1]);

This regex will return your class name

这个正则表达式将返回您的类名

#1


13  

Browsers are good in HTML parsing:

浏览器很适合HTML解析:

//setup
var tmp = document.createElement('div');
tmp.innerHTML = ddd;

// get the class
var class_name = tmp.children[0].className;

#2


0  

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> 
 <html>
   <head>
     <title>Ejemplo</title>
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
       <script type="text/javascript">
           $(document).ready(function() {
                var ddd="<p class='Box_title'>Heading text here...</p>";
                $('.container').append(ddd);
                alert($('.container').children(':first-child').attr("class"));
        });
       </script>
   </head>
   <body>
     <div class="container">
    </div>
   </body>
 </html>

#3


-2  

   var RegExp = /class='(.+)'/;
   var result = RegExp.exec("<p class='Box_title'>Heading text here...</p>");

this will return an array with class name as one of it's elements

这将返回一个类名作为其中一个元素的数组

#4


-2  

var d = "<p class='Box_title'>Heading text here...</p>";
var cls = d.match(/class\=\'(.*)\'/);
alert(cls[1]);

This regex will return your class name

这个正则表达式将返回您的类名