将元素添加到元素内部的其他元素之上

时间:2016-10-31 08:22:07

标签: jquery html

是否可以将span元素内的元素追加到其他内容的父span的顶部?

HTML

<span id="parent">
    <!-- I want the oldest placed here when something is click -->
    <span id="child1">sample1</span>
    <span id="child2">sample2</span>
    <span id="child3">sample3</span>
<span> 

 <button id="write_IT">Put the older!</button>
<!--
     //from php database

     <span id="oldest">
         Test
     </span>
-->

jquery的

$(document).ready(function() {
  $(document).on('click', '#write_IT', function(e) {

    var apb = $("#parent").after("<span id='parent'>");
    apb.append('<span id="oldest">Test</span>');
  });

});  

2 个答案:

答案 0 :(得分:1)

使用prepend

&#13;
&#13;
$('#write_IT').on("click", function(){
  $("#parent").prepend('<span id="oldest">Test</span>');
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span id="parent">
    <!-- I want the oldest placed here when something is click -->
    <span id="child1">sample1</span>
    <span id="child2">sample2</span>
    <span id="child3">sample3</span>
<span> 

<button id="write_IT">Put the older!</button>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

&#13;
&#13;
$(document).ready(function() {
  $(document).on('click', '#write_IT', function(e) {

    $("#child1").before('<span id="oldest">Test</span>');

  });

});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span id="parent">
    <!-- I want the oldest placed here when something is click -->
    <span id="child1">sample1</span>
<span id="child2">sample2</span>
<span id="child3">sample3</span>
<span> 

 <button id="write_IT">Put the older!</button>
<!--
     //from php database

     <span id="oldest">
         Test
     </span>
-->
&#13;
&#13;
&#13;

使用.before()

  

描述:在匹配元素集中的每个元素之前插入由参数指定的内容。