在 JavaScript 中获取 CSS 类名
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7468551/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 02:24:38 来源:igfitidea点击:
Get CSS class name in JavaScript
提问by Anil
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 标签的类名。
回答by Felix Kling
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;
回答by GoRoS
<!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>
回答by Headshota
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
这将返回一个类名作为其元素之一的数组
回答by Senad Me?kin
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
此正则表达式将返回您的班级名称