0

I'm using an HTML snippet to insert some text into the element, then display it somewhere:

var elemTemp = $('<span /><strong class="value unit" />').find('span').text('hi!').end();
elemTemp.appendTo('#someDiv');

I want to insert "hi" inside the span but could not get it working. The find() method doesn't seem to find the span.

2
  • It looks like your selector is wrong: $('<span /><strong class="value unit" />') Commented Oct 7, 2011 at 12:53
  • Nideo, the selector is fine, it wraps span tags around the strong element and creates a jquery object out of that. Commented Oct 7, 2011 at 12:59

3 Answers 3

5

find looks down the DOM tree, but your span is not a descendant, so find won't find it. Use siblings instead:

var elemTemp = $('<span /><strong class="value unit" />').siblings('span').text('hi!').end();

Here's a working example. Note that this produces HTML along the lines of:

<span>hi!</span>
<strong class="value unit"></strong>

I'm not sure if you were aiming for that, or if you wanted the strong to be a child of the span.

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

1 Comment

Thanks, I exactly trying to do this and your solution is worked. I'm using the <span> as a label for <strong>, which looks like a disabled input area in my application.
1

Why not do this as simply and quickly as possible?

 $('#someDiv').append('<span>hi!</span>'); // or whatever HTML you want in there

1 Comment

Thank you for the answer, but I included the elemTemp.appendTo('#someDiv'); line for simplicity. In actual application, this container element also creating programmatically by parsing some AJAX responses and some application logic. I want to append the elemTemp element while the container element is creating.
0

You have to specify which span-tag you want to insert "hi" into. The easiest way is to set a class on the span-tag.

HTML:

<span class="hello"></span>

jQuery:

$('span.hello').html('hi');

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.