開発者ドキュメント

jQuery before()とinsertBefore()の例

jQuery

before()

および

insertBefore()

メソッドは、同じタスクを実行しています。一致した要素の前にテキストまたはhtmlコンテンツを追加します。主な違いは構文にあります。

例えば、

<div class="prettyBox">I'm a ipman</div>
<div class="prettyBox">I'm a ipman 2</div>

1. $( ‘セレクター’). before( ‘new content’);

$('.prettyBox').before("<div class='newPrettybox'>Iron man</div>");

2. $( ‘新しいコンテンツ’). insertBefore( ‘selector’);

$("<div class='newPrettybox'>Iron man</div>").insertBefore('.prettyBox');

結果

上記の両方のメソッドは同じタスクを実行していますが、構文が異なると、

before()

または

insertBefore()

の後の新しい内容は

<div class='newPrettybox'>Iron man</div>
<div class="prettyBox">
   I'm a ipman
</div>

<div class='newPrettybox'>Iron man</div>
<div class="prettyBox">
   I'm a ipman 2
</div>

自分で試してみてください

<html>
<head>
<script type="text/javascript" src="jquery-1.3.2.min.js"></script>

<style type="text/css">
    .prettyBox{
        padding:8px;
        background: grey;
        margin-bottom:8px;
        width:300px;
        height:100px;
    }
    .newPrettybox{
        padding:8px;
        background: red;
        margin-bottom:8px;
        width:200px;
        height:50px;
    }
</style>

</head>
<body>
  <h1>jQuery before() and insertBefore() example</h1>

  <div class="prettyBox">Ip man</div>

  <div class="prettyBox">Ip man 2</div>

  <p>
  <button id="before">before()</button>
  <button id="insertBefore">insertBefore()</button>
  <button id="reset">reset</button>
  </p>

<script type="text/javascript">

    $("#before").click(function () {

      $('.prettyBox').before("<div class='newPrettybox'>Iron man</div>");

    });

    $("#insertBefore").click(function () {

      $("<div class='newPrettybox'>Iron man</div>").insertBefore('.prettyBox');

    });

    $("#reset").click(function () {
      location.reload();
    });

</script>
</body>
</html>
モバイルバージョンを終了