Reputation: 83
how can I get the div id from a text? I only found Text from div.
<div id="randomdiv">Text</div>
Upvotes: 1
Views: 3331
Reputation: 10874
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!).
Upvotes: 2
Reputation: 1048
var id = $(":contains('Text')").attr('id');
This will Return All elements which contains the text "Text"
Upvotes: -1
Reputation: 3678
var divId = $("div:contains('Text')").attr('id');
alert(divId); //divId is the div's id you need;
Upvotes: 4
Reputation: 10927
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.
Upvotes: 4