vinnitu
vinnitu

Reputation: 4364

how to find element after some text with javascript?

I have a HTML file with some text (like 'bla-bla') inside. I want to get a specific element (like <a href=...) after this text node.

How can I do that with pure JavaScript or jQuery?

example HTML:

<div>
  jdlgjalfad dfaldfdalf bla-bla fdfadf afd <br/> 
  <table>...
    <td></td>
  </table>
  <a href="some_link">here</a>
</div>

Upvotes: 1

Views: 1092

Answers (2)

nextdude
nextdude

Reputation: 11

$('div:contains('bla-bla')).find('a') 

will work in your example, but may not work for your real use-case. The :contains selector will find a div with some string in it, but you may need to use a regular expression to find the specific text you want if you need more context:

$('div').each(function(){
  if (/funky-regex/.test($(this).text())) {
    $(this).find('a').doSomethingHere();
  }
});

replacing doSomethingHere() with one or more jquery methods. The appropriate choice will depend on your specific use case.

Upvotes: 1

tvanfosson
tvanfosson

Reputation: 532435

You can use contains to find the elements that contain the selected text, then iterate over each, replacing the text with new text with the substitution based on your search string. Be aware that contains will return a match even if the elements descendants contain the text so you should probably specify some element type if you have nested elements or filter based on whether the element has inner elements.

$('div:contains("bla-bla")').each( function() {
   var txt = $(this).text();
   var insert = 'bla-bla<a href="...">(link)</a>';
   $(this).text( txt.replace( /bla-bla/g, insert ) );
});

or

$(':contains("bla-bla")')
    .filter( function() { return $(this).children().length == 0; } )
    .each( function() {
       var txt = $(this).text();
       var insert = 'bla-bla<a href="...">(link)</a>';
       $(this).text( txt.replace( /bla-bla/g, insert ) );
});

Upvotes: 0

Related Questions