Reputation: 31
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);
Upvotes: 2
Views: 1592
Reputation: 2337
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>" );
Upvotes: 1
Reputation: 167962
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 );
Upvotes: 0