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?

Mohammad
  • 21,175
  • 15
  • 55
  • 84
jjj
  • 2,594
  • 7
  • 36
  • 57

5 Answers5

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>
Mohammad
  • 21,175
  • 15
  • 55
  • 84
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. :)

user3771102
  • 558
  • 2
  • 8
  • 27
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>
Endless
  • 34,080
  • 13
  • 108
  • 131
  • 1
    But it would return any ancestor of div containing text too if this div is wrapped inside any other div – A. Wolff Dec 01 '16 at 09:24
  • I need to know the class name. How is this outputting name of the class that contains the unique text? – jjj Dec 01 '16 at 09:25
  • Changed so it returns the class name – Endless Dec 01 '16 at 09:30
  • Still this failed e.g [here](https://jsfiddle.net/46kws8dq/). A workaround could be to use `$("div:contains('John'):not(:has(:contains('John')))")` but still `:contains()` isn't a strict matching filter – A. Wolff Dec 01 '16 at 09:36
  • can still be useful if you are searching for some text like `John Bob` where the word is seperated `
    John
    bob
    ` but it's also possible to use `:last`
    – Endless Dec 01 '16 at 09:41
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);
    }

}
Ataur Rahman Munna
  • 3,887
  • 1
  • 23
  • 34
  • I like this way, as it's a pure JavaScript, no reliance on jQuery. I've tested it in this plunk: https://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? – jjj Dec 01 '16 at 09:47
  • 1
    If you like pure js then why did you tag your question with jQuery? – Endless Dec 01 '16 at 09:54
  • @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 Dec 01 '16 at 09:58
  • @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`. – Ataur Rahman Munna Dec 01 '16 at 11:09
  • You used jquery in code but select element by javascript! – Mohammad Dec 02 '16 at 08:05
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.

Amadan
  • 191,408
  • 23
  • 240
  • 301