Tuesday, 15 March 2011

javascript - how to select my first child in jQuery -



javascript - how to select my first child in jQuery -

this question has reply here:

jquery first kid of “this” 9 answers

i'm having bit of problem selecting first kid in jquery. i'm trying avoid having lots of if statements. basically, click on button. class selector setup handle click in js. 1 time go js, want kid of item clicked, i'm not having joy.

here's have in js:

$('.itemclicked').click(function(){ var id = $(this).attr('id').first(); // can't find method first() here. if find id, // right id of clicked. var test = id.first(); // tried above seperate id first() method request // no joy either. test.toggleclass("icon-tick"); // ultimate aim, toggle icon-tick class on item // clicked. });

thanks in advance if can help me out here. i'm doing stupid i'm struggling realise is.

your current version doesn't work because .attr('id') returns id string, not jquery object. also, .first() returns first item jquery collection, not children.

so, want:

var test = $(this).children().first();

or:

var test = $('>:first-child', this);

or:

var test = $(this).children(':first');

or (on newer browsers):

var test = $(this.firstelementchild);

in jsperf test chrome 25 .firstelementchild method incredibly fast, it's not available on msie < 9. .children().first()was fastest portable option, , the>:first-child' method very, slow.

javascript jquery css-selectors

No comments:

Post a Comment