Select the special selector after the $ (this) selector

for example i have this code

<script>

$(document).ready(function () {     
    $('span').each(function () {    

        $(this).html('<div></div>') ;    
        if ( $(this).attr('id') == 'W0' ) { $( this > div ?!!! ).text('0') }
        if ( $(this).attr('id') == 'W1' ) { $( this > div ?!!! ).text('1') }
        if ( $(this).attr('id') == 'W2' ) { $( this > div ?!!! ).text('2') }

    });     
});

</script>

<span id="W0"></span>
<span id="W1"></span>
<span id="W2"></span>

      

But $( this > div )

or $( this ' > div ' )

are the wrong selector and don't work

So what guys am I suggesting to do?

+3


source to share


2 answers


You can use it like this:

$(' > div', $(this))

      

Docs: http://api.jquery.com/child-selector/

OR

For direct children, you can use children

:

$(this).children('div')

      



Docs: http://api.jquery.com/children/

OR

Using find

$(this).find(' > div')

      

Docs: http://api.jquery.com/find/

Demo

+8


source


You can pass context to jQuery along with a selector

$(' > div ', this )

      

or use children () like

$(this).children('div')

      




But your decision can be done like

$(document).ready(function() {
  var texts = {
    W0: '0',
    W1: '1',
    W2: '2'
  }
  $('span').each(function() {
    $('<div />', {
      text: texts[this.id]
    }).appendTo(this)

  });
});
      

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<span id="W0"></span>
<span id="W1"></span>
<span id="W2"></span>
      

Run codeHide result


+6


source







All Articles