3
<div id="foo">yyy<span>xxx</span></div>

I have the the above structure for my html. I want to insert some content at yyy position. Can you let me know what will be the selector for it? I would pass that selector to somefunction and that function will do $(selector).html('content')

Rocky Singh
  • 15,128
  • 29
  • 99
  • 146

5 Answers5

6
var s = $('#foo span');
$('#foo').text("hello").append(s);

Demo: http://jsfiddle.net/uTNTF/

Or, if updating the HTML is an option, then simply wrapping yyy in a <span> will make your life a lot simpler:

$('#foo span:first-child').text("hello");

Demo: http://jsfiddle.net/uTNTF/1/

Shawn Chin
  • 84,080
  • 19
  • 162
  • 191
2

You can use jQuery .prepend() function (insert content, specified by the parameter, to the beginning of each element in the set of matched elements):

$('#foo').prepend('some content');
Hck
  • 9,087
  • 2
  • 30
  • 25
1

yyy should rellay be in a block element to allow you to easily discover it, otherwise I see no option other than the hacky:

$('#foo').html($('#foo').html().replace('yyy','')).find('span').before('new content');

Live example: http://jsfiddle.net/MTu6c/

Jamiec
  • 133,658
  • 13
  • 134
  • 193
0

I don't think there is a single magic selector that will select some plain text inside a container but not all of of the content.

If you want to replace 'yyy' with 'some content', you could do something like the following:

$('#foo').html('some content' + $('#foo span').html())
AaronShockley
  • 851
  • 5
  • 4
0

The "yyy" portion of the markup you posted is represented in the DOM as a text node. jQuery doesn't have any methods or selectors for isolating text nodes, but the DOM does.

See here (your question might be considered a duplicate of this one): How do I select text nodes with jQuery?

Community
  • 1
  • 1
Ian Clelland
  • 43,011
  • 8
  • 86
  • 87