10

i've got this:

<div class="" id="fancy_hover">
    <a href="home.html" id="start_writer"></a>  
    <div>
        <p class="hidden" style="display: block;">click here to see this event with all the bells and whistles</p>
    </div>
</div>

I need to do an equivalent of .find() but for the string "click here" instead of a node, i then need to wrap it in an <a> tag.

Whats the best approach with jquery?

Haroldo
  • 36,607
  • 46
  • 127
  • 169

2 Answers2

21

Use :contains filter selector:

$('p.hidden:contains("click here")')

To wrap it in link:

$('p.hidden:contains("click here")').html()
.replace('click here', '<a href="url">click here</a>');

To wrap whole text in link:

$('p.hidden:contains("click here")')
.html('<a href="url">' + $('p.hidden:contains("click here")').text() + '<a>');

More Info:

Sarfraz
  • 377,238
  • 77
  • 533
  • 578
9

Don't use HTML string hacking. Imagine what would happen if you tried to replace over <span title="blah click here blah">...</span> with an <a> tag... massively broken markup. And that's only the beginning of the problems.

Instead, iterate over the text nodes in the part of the document you want to examine, looking for text matches and inserting a new link using DOM-style methods.

jQuery doesn't really help you much here as it has no functionality for handling text nodes. Instead, use something like the findText() function from this question and use splitText to split up the text node:

findText($('#fancy_hover')[0], /\bClick here\b/gi, function(node, match) {
    node.splitText(match.index+match[0].length);
    var link= document.createElement('a');
    link.href= 'http://www.example.com/';
    link.appendChild(node.splitText(match.index));
    node.parentNode.insertBefore(link, node.nextSibling);
});
Community
  • 1
  • 1
bobince
  • 528,062
  • 107
  • 651
  • 834