Add id to tag based on text it contains
I need to add an "id" to the h2 based on开发者_开发知识库 the text it contains. What I have is not working.
Starts like this
<h2>Revision 3</h2>
Scripts runs
$('h2:contains(" Revision 3 ")').replaceWith( "<h2 id="rev3">Revision 3</h2>");
Ends like this
<h2 id="rev3">Revision 3</h2>
$('h2').each(function ()
{
if ($(this).text() == "Revision 3")
$(this).attr('id','rev3');
}
Loops through all h2 tags, if the tag text is Revision 3
it set the id to rev3
Or if you just want to add ID to it you might use something faster like:
$('h2:contains("Revision 3")').attr('id','rev3');
You can't quote a string within a string using the string delimiters...so you can't use "
inside a string delimited with "
, but you could use '
inside a string delimited with "
). For example:
$('h2:contains(" Revision 3 ")').replaceWith( "<h2 id='rev3'>Revision 3</h2>");
Should work. Also, the spaces at the beginning, and end, of the string should be removed, since they're not in the string you're looking for:
$('h2:contains("Revision 3")').replaceWith( "<h2 id='rev3'>Revision 3</h2>");
And, finally, would it not be easier to use something like:
$('h2:contains("Revision 3")').attr('id','rev3');
Given that an id
must be unique within a document it's maybe also worth limiting the selector to only one element:
$('h2:contains("Revision 3")').eq(0).attr('id','rev3');
$('h2:contains("Revision 3")').attr("id", "rev3");
I think the extract spaces at the begin and end of Revision 3 are creating an issue.
Try this:
$('h2:contains("Revision 3")').replaceWith( "<h2 id="rev3">Revision 3</h2>");
精彩评论