2

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?

1

5 Answers 5

3

JQuery :contains selector select element has specific text but it isn't exact. For example

$("div:contains(UniqueText)")

Select both of bottom divs

<div class="_className">UniqueText</div>
<div class="_className2">UniqueText2</div>

You can use .filter() to filter selected element by text.

var className = $("*").filter(function(){
    return $(this).text() == "UniqueText";
}).attr("class");

var className = $("*").filter(function(){
    return $(this).text() == "UniqueText";
}).attr("class");

console.log(className);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="_className">UniqueText</div>
<div class="_className2">UniqueText2</div>

Sign up to request clarification or add additional context in comments.

Comments

3

By getting all the div with each function you can search through all the divs and place a condition in which you the value of the div is equal to the particular text that you want to find. Then get the class name by using .attr('class').

 $( "div" ).each(function(){
       if($(this).text() == "UniqueText"){
        var output = $(this).attr('class');
        $(".output").html(output);
       }
 });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="_classname">UniqueText</div>

<div class="output"></div>

It might be a bit long for a code but it gets the work done nicely. :)

2 Comments

I like this... thanks a lot. Will it work for nested DIVs as well?
Yes as long as it is a div. It will search for all the <div> tags.
2

You can use :contains(word)

var className = $( "div:contains('John')" ).attr("class");
console.log(className)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="foo">John Resig</div>
<div class="bar">George Martin</div>
<div class="foo">Malcom John Sinclair</div>
<div class="baz">J. Ohn</div>

5 Comments

But it would return any ancestor of div containing text too if this div is wrapped inside any other div
I need to know the class name. How is this outputting name of the class that contains the unique text?
Changed so it returns the class name
Still this failed e.g here. A workaround could be to use $("div:contains('John'):not(:has(:contains('John')))") but still :contains() isn't a strict matching filter
can still be useful if you are searching for some text like John Bob where the word is seperated <div><i>John</i><br><i>bob</i><div> but it's also possible to use :last
1

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

}

5 Comments

I like this way, as it's a pure JavaScript, no reliance on jQuery. I've tested it in this plunk: embed.plnkr.co/T5FLMg5oCq41p2H22A1w . The only issue I see is that it doesn't output all occurrences. How would you go about looping through all results?
If you like pure js then why did you tag your question with jQuery?
@Endless, I've asked for JavaScript or jQuery, but why would I load jQuery and inflate the size of my script, if there is a pure JavaScript one liner that can do this. Please don't be offended, but this is in my opinion a most elegant way of achieving the result.
@jjj you can iterate your all div by using document.getElementsByTagName("div"); this. noted that this only works for simple div, not for nested div.
You used jquery in code but select element by javascript!
1

This should be faster than using jQuery (but a bit more to type):

var xpath = "//div[text()='UniqueText']";
var result = document.evaluate(xpath,
    document, null, XPathResult.FIRST_ORDERED_NODE_TYPE);
var node = result.singleNodeValue;
if (node) {
  console.log(node.className);
} else {
  console.error("Not found!");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="_className">UniqueText</div>

The reason is, browser's CSS selectors don't support :contains selector, and jQuery needs to emulate it by checking every node matching the rest of the selector. Ditto for using .filter. But XPath is done natively by the browser.

You also cannot specify exact match using the jQuery :contains, like here. If substring matching was indeed needed, you can change the XPath:

var xpath = "//div[contains(text(),'UniqueText')]";

XPath is very powerful, but a bit finicky and largely unknown, so I find it is very under-utilised, even when its use would be a perfect fit.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.