You need to place a div inside a div with a constantly changing id. The only criterion you can find is the text inside the div. Is it possible to get the id of the element in the text inside it? Example:

<div id="123-dx-fe45">Привет</div> 

You need to know the id div in which there is the word Привет (using only javascript).

  • You can select all divs to filter those that contain a text node containing the desired word, take id - Grundy
  • It is much better and easier to search for other criteria. - Qwertiy

3 answers 3

 ~function () { var divs = document.querySelectorAll("div[id]"); for (var q=0; q<divs.length; ++q) { if (!divs[q].firstElementChild && divs[q].textContent.match(/Привет/i)) { divs[q].className = 'found'; } } }(); 
 .found:after { content: " - " attr(id); color: red; } 
 <div id="any"> <div id="1">Привет</div> <div id="2">Пока</div> <div id="3">И тебе привет</div> <div>Привет</div> </div> <div id="4">Привет</div> <div id="5"><span>Привет</span></div> <div id="6"> Привет </div> <div id="7"> Всем привет! </div> 

  • why don't you think so? <div id="1">Привет, <span>1</span></div> - Grundy
  • @Grundy, but this is not asked to be considered, like? - Qwertiy
  • But I'm not sure what exactly the author needs :-) - Grundy

For example:

 function getBlocksWithText(selector, text) { var elements = document.querySelectorAll(selector); var regexp = new RegExp(text, 'i'); return Array.prototype.filter.call( elements, function(el) { return el.textContent.search(regexp) !== -1; } ); } var elements = getBlocksWithText('div', 'Привет'); var retStr = elements.map(function(el) { return el.id }).join(); alert(retStr); 
 <div id="1">Привет</div> <div id="2">Пока</div> <div id="3">И тебе привет</div> 

  • does not work correctly if div with text is nested, for example, if you put div with id = 3, diva with id = 2, then the result will be 1,2,3 , but not 1,3 as expected - Grundy
 $('div:contains("Привет")').attr('id'); 
  • in the absence of library labels, a solution is expected in javascript without using them - Grundy
  • In addition, this option will return the container id , and not directly the diva in which the text is located - Grundy