HOME > > > > >

.before( content [, content ] )

.before( content [, content] )

引数

content
html|DOM element|jQuery object

戻り値

jQuery
jQueryオブジェクト

サンプル

jQueryオブジェクトが保持しているDOM要素の前にcontentを追加する。戻り値は1.9で変更となった。

実行結果

実行

test1

test2

test3

Javascript

  1. $('#code1-execute').on('click', function(e) {
  2.  
  3.     var result = $('#code-sample1 p').before($('<span>', {
  4.         text: 'before',
  5.         css: {fontWeight: 'bold', color: 'red'}
  6.     }));
  7.  
  8.     // beforeの戻り値を .return-value に追加
  9.     // 1.9 で動作が変更になったらしい
  10.     $('#code-sample1 .return-value').prepend(result.clone());
  11. });
  12.  
  13.  

HTML

  1. <span class="btn btn-execute" id="code1-execute">実行</span>
  2.  
  3. <div id="code-sample1">
  4.     <p>test1</p>
  5.     <p>test2</p>
  6.     <p>test3</p>
  7.  
  8.     <div class="return-value">
  9.  
  10.     </div>
  11. </div>

CSS

  1. #code-sample1 .return-value {
  2.     background: #EEEFFF;
  3.     padding: 8px;
  4. }
  5.  

.before( function )

引数

function
function

戻り値

jQuery
jQueryオブジェクト

function は html|DOM element|jQuery object を返すようにする。 function内での this は jQueryオブジェクト内のDOMが順に入る。index はjQueryオブジェクト内でのIndex番号。

サンプル

実行結果

実行

test1

test2

test3

Javascript

  1. $('#code2-execute').on('click', function(e) {
  2.  
  3.     var result = $('#code-sample2 p').before(function(index){
  4.         return $('<span>', {
  5.             text: 'before ' + $(this).text() + '/ index ' + index,
  6.             css: {fontWeight: 'bold', color: 'red'}
  7.         });
  8.     });
  9.  
  10. });
  11.  
  12.  

HTML

  1. <span class="btn btn-execute" id="code2-execute">実行</span>
  2.  
  3. <div id="code-sample2">
  4.     <p>test1</p>
  5.     <p>test2</p>
  6.     <p>test3</p>
  7. </div>

CSS

  1. #code-sample2 .return-value {
  2.     background: #EEEFFF;
  3.     padding: 8px;
  4. }
  5.