Sometimes Code
Sometimes Code

Reputation: 601

How can i insert html element between start and end tag of another html element using jquery

I have a textbox :

    <input type="text"></input>

I want to add a span between the input element using jquery like the below:

    <input type="text"><span>Added span</span></input>

How can I achieve that?

Upvotes: 1

Views: 1343

Answers (5)

RobH
RobH

Reputation: 3612

You can't put a <span> (or any element) into a text input. Look at this fiddle: http://jsfiddle.net/GAFTk/

Your browser will change it to:

<input type="text" /><span>Text</span>

and render them side by side.

Upvotes: 1

Hidde
Hidde

Reputation: 11911

I will answer three questions:

How to append some HTML in an element?

Use jQuery: $('div').append('<span>Added span</span>');

How to add a placeholder to an input element?

Use the following markup: <input type="text" placeholder="My placeholder" /> (Browser support: http://caniuse.com/input-placeholder)

How to add text by default in my input?

Use the following markup: <input type="text" value="My text" />

Upvotes: 3

Matthijs
Matthijs

Reputation: 1142

First:

<input id="inserthere" type="text"></input>

then:

$('#inserthere').innerHtml('<span>Added span</span>');

Result:

<input id="inserthere" type="text"><span>Added span</span></input>

edit: almost forget you can also use the jQuery "append" method if you want to ADD something instead of overwrite it!

Upvotes: -1

Louis Ricci
Louis Ricci

Reputation: 21086

You don't want to put html elements inside of input elements, but in general you use jQuery.append()

<div id="demo"></div>
<script>$("#demo").append("<span>added span</span>");</script>

Result:

<div id="demo"><span>added span</span></div>

If you append something else it won't remove whats already in there.

<script>$("#demo").append("<span>another</span>");</script>

<div id="demo"><span>added span</span><span>another</span></div>

If you want to overwrite whats already inside you'd use .html instead of .append, or .empty and then .append

Upvotes: 0

M Shahzad Khan
M Shahzad Khan

Reputation: 935

$('#inputId').innerHtml('<span>adding span</span>');

Upvotes: -1

Related Questions