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')

5 Answers 5

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/

Sign up to request clarification or add additional context in comments.

1 Comment

This is probably the cleanest way to do it.
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');

2 Comments

alternatively $('#foo span').before(...). (esp if you had multiple elements and wanted something inserted between them)
This will not remove 'yyy' and insert my content.
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/

Comments

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())

Comments

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?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.