Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using jQuery, how to modify text outside of tags?

Given a string of text that is both adjacent to a span and inside of a div, what are some methods to modify just that text, leaving the surrounding HTML intact? For example:

<div id="my-div">modify this text<span id="my-span"></span></div>

I have tried things like

$('#my-div').html(function(i, elem){blah;});

but this seems to cause the span to be deleted and a new span to be added (I notice that some styling is lost on the span).

I realize that it would be best to wrap the text string in its own HTML tags before applying client-side code, but that is out of my control.

like image 648
Jacob Marble Avatar asked Dec 17 '22 01:12

Jacob Marble


2 Answers

This seems to work:

$('#my-div').contents()
            .filter(function() { return this.nodeType == 3; })
            .replaceWith('new text or html');

nodeType == 3 is to test for a text node.

like image 182
Siddhartha Reddy Avatar answered Dec 28 '22 12:12

Siddhartha Reddy


What about using jQuery's contents() method?

http://api.jquery.com/contents/

like image 21
alex Avatar answered Dec 28 '22 11:12

alex