Can I use jQuery to locate a string of text within the HTML?
I'm just starting to learn about jQuery and am becoming familiar with how jQuery allows me to use selectors to search for particular IDs and classes. But is it also possible to identify strings of plain old text inside a paragraph?
For exa开发者_如何转开发mple, say I wanted to find "gasoline" within these paragraph tags and convert it into a link:
<p>His veins burned gasoline.
It kept his motor running but it never kept him clean.</p>
You wouldn't really use jQuery to do the replace. Instead just use javascript's .replace()
method.
(I gave the paragraph an ID to specify the correct paragraph.)
Try it out: http://jsfiddle.net/yRCjN/1/
HTML
<p id='myparagraph'>His veins burned gasoline.
It kept his motor running but it never kept him clean.</p>
javascript/jQuery
// Cache the selected element so it only runs once.
var $paragraph = $('#myparagraph');
// Get the text and update it with the <a> tag
var newcontent = $paragraph.text().replace(/(gasoline)/,'<a href="/some/link/path">$1</a>');
// Set the new content
$paragraph.html( newcontent );
- You get the content of the paragraph using jQuery's
.text()
- Do a
.replace()
on the text content replacing "gasoline" with the same text wrapped in an<a>
element Use jQuery's
.html()
method to update the paragraph with the new content.http://api.jquery.com/text/
- http://api.jquery.com/html/
Park Avenue leads to...
var text = jQuery("#someId").text();
text = textreplace(/(gasoline)/, "<a href='http://some.url.here'>$1</a>");
jQuery("#someId").html(text);
$('p').text().replace('gasoline', '<a href="#">gasoline</a>');
精彩评论