How to find an element after some text using javascript?

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

How can I do this using pure JavaScript or jQuery?

HTML example:

 <div> jdlgjalfad dfaldfdalf bla-bla fdfadf afd <br/> <table>... <td></td> </table> <a href="some_link">here</a> </div> 
+1
source share
2 answers

You can use contains to find elements that contain the selected text, then iterate over each one, replacing the text with the new text with a wildcard based on your search string. Keep in mind that contains will return a match even if descendant elements contain text, so you should probably specify some type of element if you have nested elements or a filter based on whether the element contains internal 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 ) ); }); 
0
source
 $('div:contains('bla-bla')).find('a') 

will work in your example, but may not work for your actual use. Selector: contains a selector with some string in it, but you may need to use a regular expression to find the text you need if you need more context:

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

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

0
source

Source: https://habr.com/ru/post/1387517/


All Articles