2

I am facing a problem to get the class name from a string in 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.

mr.b
  • 4,932
  • 11
  • 38
  • 55
Anil
  • 31
  • 1
  • 1
  • 2

4 Answers4

13

Browsers are good in HTML parsing:

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

// get the class
var class_name = tmp.children[0].className;
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
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>
GoRoS
  • 5,183
  • 2
  • 43
  • 66
-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

Headshota
  • 21,021
  • 11
  • 61
  • 82
  • seriously, why would you use regex for this when you've got an HTML parser right there ready to use? – Spudley Sep 19 '11 at 14:51
-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

Senad Meškin
  • 13,597
  • 4
  • 37
  • 55
  • the you are writing it wrong, I have tested it and its working, if you are using firebug, just paste my code into console and run it – Senad Meškin Sep 19 '11 at 10:26