1

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>
3
  • 2
    Please post a snippet of your HTML. It's difficult to post a good answer when you're so nonspecific. Commented Mar 13, 2011 at 18:17
  • Which specific node? Just the next node? You want something specific without providing a proper example. Commented Mar 13, 2011 at 18:39
  • please can you see my example Commented Mar 13, 2011 at 19:07

2 Answers 2

1
$('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.

Sign up to request clarification or add additional context in comments.

Comments

0

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 ) );
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.