1

how can I get the div id from a text? I only found Text from div.

<div id="randomdiv">Text</div>
GillesC
  • 10,647
  • 3
  • 40
  • 55
LosAngeles
  • 83
  • 1
  • 11
  • 3
    @ReCaptcha We don't know that the OP uses jQuery. – afaolek Jul 15 '14 at 12:31
  • 2
    You can use [`getElementsByTagName('*')`](http://www.w3.org/TR/DOM-Level-3-Core/core.html#ID-A6C9094) to get all the elements in say the body, then loop over them looking for the one whose [*textContent*](http://www.w3.org/TR/DOM-Level-3-Core/core.html#Node3-textContent) is, or includes, the text you seek. – RobG Jul 15 '14 at 12:32

4 Answers4

4

If you're using jQuery things are really easy.

var src = "Text"; // what to look for

$('*:contains("'+src.replace(/\"/g, '\"')+'")') // search all elements containing that text, also replace double quotes because it might break the selector
    .filter( function(){ 
        return $(this).text()==src;  // check for exact matches (this is slow btw)
    })
    .first() // retrieve the first element. you have to adjust if you're looking for all elements
    .attr('id'); // retrieve the id. this is semantic. it's faster to use [0].id instead of this

If you're not using jQuery you'll probably have 30-40 lines of code doing just this.

Silviu-Marian
  • 10,565
  • 6
  • 50
  • 72
  • 1
    `[id]` instead of `*` in the selector would improve performance as it would avoid looping over elements which do not have an id but contains text. Or `body [id]` if targeting elements in the body only. – GillesC Jul 15 '14 at 12:52
4
var divId = $("div:contains('Text')").attr('id');

alert(divId);  //divId is the div's id you need;
Alien
  • 3,658
  • 1
  • 16
  • 33
  • Important to note that if there is more than one element containing `Text` and having an `id` only the first one will be returned using this approach. – GillesC Jul 15 '14 at 13:26
  • By the way, this function doesn't check to see if "Text" is the only thing inside that element. – Silviu-Marian Jul 16 '14 at 18:04
1

In pure javascript it's actually quite simple too.

Here is a little helper function which returns an array of ids base on a search string. If the second argument is true it will do a basic partial search instead of a strict check.

Javascript

NodeList.prototype.forEach = Array.prototype.forEach;

function getElementIdsByText(search, partial) {

    var elements = document.querySelectorAll("[id]");
    var ids = [];

    elements.forEach(function(element) {
        if (!partial && element.textContent === search) {
            ids.push(element.id);
        }

        if (partial && element.textContent.indexOf(search) !== -1) {
            ids.push(element.id);
        }
    });

    return ids;
}

console.log(getElementIdsByText("Text"));
console.log(getElementIdsByText("Fo", true));

HTML

<div id="randomdiv">Text</div>
<div id="randomdiv2">Text</div>
<div id="fooDiv">Foo</div>

Output

["randomdiv", "randomdiv2"]
["fooDiv"] 

The NodeList.prototype.forEach = Array.prototype.forEach; is not needed of course you can use the slice method too to convert it to a normal array, but in theory the slice method is not guaranteed (not that I know if this one is!).

http://jsfiddle.net/A4XkY/2/

GillesC
  • 10,647
  • 3
  • 40
  • 55
-1
var id = $(":contains('Text')").attr('id');

This will Return All elements which contains the text "Text"

SysDragon
  • 9,692
  • 15
  • 60
  • 89
kheengz
  • 840
  • 12
  • 10