Danin Na
Danin Na

Reputation: 409

select special selector after $(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 wrong selector & doesn't work

So what do u guys suggest I should do ?

Upvotes: 3

Views: 147

Answers (2)

Tushar
Tushar

Reputation: 87203

You can use it as follow:

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

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

OR

For direct child elements, 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

Upvotes: 8

Arun P Johny
Arun P Johny

Reputation: 388316

You can pass a context to jQuery along with the selector

$(' > div ', this )

or use children() like

$(this).children('div')

But your solution can be done as

$(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>

Upvotes: 6

Related Questions