Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to surround this text that hasn't any HTML tags around it (with jQuery)?

Tags:

html

jquery

<span id="subscription-toggle" class="list:subscription">

&nbsp;|&nbsp; <!-- I want to surround this with a div with a class -->

<span class="" id="subscribe-77" style="">
<a class="dim:subscription-toggle:subscribe-77:is-subscribed" href="http://localhost/taiwantalk2/topic/topic-with-two-tags-topic-with-two-tags-topic-with-two-tags/?action=bbp_subscribe&amp;topic_id=77&amp;_wpnonce=25988e5dac">Subscribe</a>
</span>

</span>

So this should be the final result:

<span id="subscription-toggle" class="list:subscription">

<div class="hide-this">&nbsp;|&nbsp;</div>

<span class="" id="subscribe-77" style="">
<a class="dim:subscription-toggle:subscribe-77:is-subscribed" href="http://localhost/taiwantalk2/topic/topic-with-two-tags-topic-with-two-tags-topic-with-two-tags/?action=bbp_subscribe&amp;topic_id=77&amp;_wpnonce=25988e5dac">Subscribe</a>
</span>

</span>
like image 862
alexchenco Avatar asked Jun 18 '11 09:06

alexchenco


People also ask

What is text() in jQuery?

jQuery text() Method The text() method sets or returns the text content of the selected elements. When this method is used to return content, it returns the text content of all matched elements (HTML markup will be removed). When this method is used to set content, it overwrites the content of ALL matched elements.

How do I get inner text in jQuery?

Answer: Use the jQuery text() method You can simply use the jQuery text() method to get all the text content inside an element. The text() method also return the text content of child elements.


2 Answers

If the text node you wish to wrap your div around is the only text node (i.e. it's the only text inside subscription-toggle that is not inside another element) then you can do this:

$("#subscription-toggle").contents().filter(function() {
    return this.nodeType == 3;
}).wrap("<div class='hide-this'></div>");

You can see an example here.

Alternatively, if there are multiple text nodes in the span, and you only want to wrap | characters, replace the body of the filter function with this line:

return $(this).text().indexOf("|") != -1;

You can see an example of that one working here.

like image 56
James Allardice Avatar answered Oct 11 '22 05:10

James Allardice


I haven't tested but it should work:

var subsc = $('#subscription-toggle');
subsc.html(subsc.html().replace('/(&nbsp;\|&nbsp;)/g', '<div class="hide-this">$1</div>'));
like image 44
Karolis Avatar answered Oct 11 '22 06:10

Karolis