简体   繁体   中英

Insert one HTML element before another jQuery

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

尝试这个:

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

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>" );

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM