Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery $(element).contents().first().text("new text") doesn't work?

I can't find anything about this on Google or here.

I have a div with in it, some text and some html as such:

<div id="test-div">
    http://<strong>somewebsite.com</strong>/big/long/unfriendly/path/
</div>

What I want to do, is add a <wbr> after every slash. (Because the value doesn't wrap otherwise and messes up my table). Doing a simple replace on the $('#test-div').html() will also mess with the strong tag, so that's not an option.

I figured using $('#test-div').contents() to filter out the text parts (recursively) would work. However I can't seem to edit the individual bits returned. I would expect this to change the http:// part:

$('#test-div').contents().first().text("something");

However it does nothing. I know I have my navigation right, because something like this:

$('#test-div').contents().first().wrap( "<b></b>" );

does work.

Why can't I change the text bit? (A more elegant solution to the initial problem would also be great)

like image 359
Coo Avatar asked Mar 07 '14 04:03

Coo


People also ask

How to get text from an element jQuery?

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.

How to append as first element in jQuery?

The . prepend() method inserts the specified content as the first child of each element in the jQuery collection (To insert it as the last child, use . append() ).

How to append before div in jQuery?

jQuery insertBefore() Method The insertBefore() method inserts HTML elements before the selected elements. Tip: To insert HTML elements after the selected elements, use the insertAfter() method.

Is text () a jQuery method?

jQuery text() MethodThe 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.


1 Answers

Use like this:

$('#test-div').contents().filter(function(){
    return $.trim($(this).text()) == 'http://';
}).remove().end().prepend('something');

demo

or,

$('#test-div').contents().first().remove().end().prepend("something");

demo

like image 144
Bhojendra Rauniyar Avatar answered Oct 26 '22 02:10

Bhojendra Rauniyar