jjj jjj - 6 days ago 4
HTML Question

How to get class name of element has specific text using javascript/jquery?

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?

Answer

You can keep an id for your div, as per your information your text will be unique.

<div id="UniqueText" class="_className">UniqueText</div>

and the js code will be

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)!=-1){
        var className = $('#'+text).attr('class');
        console.log(className);
    }

}