Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery: find a string and wrap it in an <a> tag?

Tags:

jquery

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?

like image 650
Haroldo Avatar asked Aug 05 '10 10:08

Haroldo


People also ask

How do I wrap text inside a div?

If you've faced the situation when you need to wrap words in a <div>, you can use the white-space property with the "pre-wrap" value to preserve whitespace by the browser and wrap the text when necessary and on line breaks. Also, you'll need the word-wrap property.

What does the jQuery wrap () function do?

jQuery wrap() method is used to wrap specified HTML elements around each selected element. The wrap () function can accept any string or object that could be passed through the $() factory function. Syntax: $(selector).

Which jQuery method allows you to add a wrapper element around another set of elements?

The wrap() method wraps specified HTML element(s) around each selected element.


1 Answers

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:

  • http://api.jquery.com/contains-selector/
like image 106
Sarfraz Avatar answered Oct 13 '22 20:10

Sarfraz