2

I wonder how to insert an HTML element before another with jQuery. It is also important to be able to get the content of the new element out of an input. Something like that, but working :

 var input = $("#theInput").val();

 var content = document.createElement("p");

 content.appendChild(document.createTextNode(input));

 $("div").insertBefore(content);
1
  • 5
    You mixed up the order, $(content).insertBefore("div");, or just $("div").before(content); Commented Dec 14, 2013 at 16:50

3 Answers 3

2

Try this:

$("div").prepend(content);
Sign up to request clarification or add additional context in comments.

Comments

1

See below example:

HTML Structure:

<div class="container">
  <h2>Greetings</h2>
  <div class="inner">Hello</div>
</div>

Jquery:

$( ".inner" ).before( "<p>Test</p>" );

Result (HTML):

<div class="container">
  <h2>Greetings</h2>
  <p>Test</p>
  <div class="inner">Hello</div>
</div>

EDIT:

Please see sample below, it takes value from text box and insert it before

HTML Structure:

<div id="content">
<input type="text" value="textboxvalue" > <br/><br/>
<span>Insert text box value befor this one</span>    
</div>

JQUERY:

var inputval = $("#content input").val();
$( "#content span" ).before( "<p>" + inputval + "</p>" );

2 Comments

It's all well, like the other examples I found in google. But could you help me out by explaining how to add my input variable to that paragraph. Cause here it is being added to the html file like text, I don't know if it can be modified
I have added a new sample above in my comment, working jsfiddle link is jsfiddle.net/Np8U8/2
0

JSFIDDLE

Option 1 - Just using jQuery:

var input = $("#theInput").val();
$("<p />")                       // Create a paragraph element.
    .text( input )               // Set the text inside the paragraph to your input.
    .insertBefore( $( "div" ) ); // Insert the paragraph before the div element(s).

Option 2 - Modifying your code:

var input = $("#theInput").val(),
    content = document.createElement("p");
content.appendChild(document.createTextNode(input));
$( content ).insertBefore( $( "div" ) );

Option 2a - Or you can change the last line to:

$( "div" ).before( content );

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.