如何使用javascript/jquery获取具有特定文本的元素的类名称? [英] How to get class name of element has specific text using javascript/jquery?
本文介绍了如何使用javascript/jquery获取具有特定文本的元素的类名称?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要一种JavaScript或jQuery的方式,通过它包含的文本提取DIV元素的类名称.
I need a JavaScript or jQuery way of extracting the Class name of DIV element by the text it contains.
让我们举例说明.如果让我说以下代码:
Let's illustrate. If I had let's say following code:
<div class="_className">UniqueText</div>
我需要知道如何以编程方式执行如下操作:
I need to to know how to programmatically do something like this:
getClassNameWhereText("UniqueText");
在这种情况下,输出应为:
In this case output should be:
_className
有没有办法做到这一点?
Is there a way to do this?
推荐答案
您可以为自己的div保留一个ID,根据您的信息,您的文本将是唯一的.
You can keep an id for your div, as per your information your text will be unique.
<div id="UniqueText" class="_className">UniqueText</div>
,js代码将是
function getClassNameWhereText(text){
var className = $('#'+text).attr('class');
console.log(className);
}
更新::如果要使用包含 那么你可以做到这一点,
UPDATE : if you want to using contains then you can do this,
function getClassNameWhereText(text){
var val = document.getElementById(text).value;
if(text.indexOf(val)>=0){
var className = $('#'+text).attr('class');
console.log(className);
}
}
这篇关于如何使用javascript/jquery获取具有特定文本的元素的类名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文