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.
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.
Share Improve this question edited Jun 22, 2015 at 15:18 mr.b 4,96211 gold badges40 silver badges56 bronze badges asked Sep 19, 2011 at 9:02 AnilAnil 311 gold badge1 silver badge2 bronze badges 3- I think this is a similar post that could help you: stackoverflow.com/questions/789675/… – GoRoS Commented Sep 19, 2011 at 9:06
- @GoRoS: That is about something totally different. – Felix Kling Commented Sep 19, 2011 at 9:18
- Ouh, ok, I've understood wrong the question – GoRoS Commented Sep 19, 2011 at 9:51
4 Answers
Reset to default 14Browsers are good in HTML parsing:
//setup
var tmp = document.createElement('div');
tmp.innerHTML = ddd;
// get the class
var class_name = tmp.children[0].className;
<!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>
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
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