JQuery $ (element) .contents (). First (). Text ("new text") not working?

I canโ€™t find anything about it on Google or here.

I have a div 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 <wbr> after each slash. (Because the value does not wrap otherwise and ruin my table). Doing a simple replacement with $('#test-div').html() would also be useless with a strong tag, so this is not an option.

I decided to use $('#test-div').contents() to filter the text parts (recursively). However, I cannot edit individual bits. I would expect this to change http: // part:

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

However, he does nothing. I know that I have the right to navigate because something like this:

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

works.

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

+6
source share
6 answers

In the end, I found my own answer thanks to these and these . Now I have a function that replaces all text in all text nodes in context. It can also embed HTML in specified nodes.

JavaScript function:

 function recursiveReplace(node, oldValue, newValue) { if (node.nodeType === 3) { // text node $(node).replaceWith(node.nodeValue.replace(oldValue, newValue)); } else if (node.nodeType === 1) { // element $(node).contents().each(function() { recursiveReplace(this, oldValue, newValue); }); } } //To call div = $('#test-div'); recursiveReplace(div[0], "/", "/<wbr />"); 

This resolved it in a general way.

0
source

Use 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

+1
source

You tried

 $(element).html('your content here'); 
0
source

How about regular expression replace / with /<wbr> ?

 $('#test-div').html($('#test-div').html().replace(/(<)?[/]/g, function($0,$1){ return $1?$0:'/<wbr>'; })); 

/(<)?[/]/g will look for all slashes, but also pay special attention to any closing tags.

return $1?$0:'/<wbr>'; will ignore </ , but replace any other / with /<wbr>

You might want to close the wbr tag.

0
source

Have you tried something like this?

 $('#test-div').html().replace('/', '/<wbr>'); 
0
source

because when you say first, it gives you [object Text] , and the text property does not work with it, the simplest solution is:

 $("#test-div").contents()[0].textContent="Something"; 

Jsfiddle demo

0
source

All Articles