JQuery - unrecognized expression :: nth-child

I am trying to select :nth-child using jquery, but it shows a syntax error.

 Error: Syntax error, unrecognized expression: :nth-child 

Here is my code

 var i; jQuery('#' + id + ' .tab-pane').each(function (id, t) { var n = jQuery(this).attr('id', 'pane-' + t); var p_id = n.attr('id'); jQuery('#' + id + ' .nav-tabs li:nth-child(' + i + ') a').attr('href', p_id); i++; }); 

please check my code is missing here.

+4
source share
3 answers

At the first iteration, there is no value for i . So the query looks like this:

 jQuery('#' + id + ' .nav-tabs li:nth-child(undefined) a').attr('href', p_id); 

In subsequent iterations, it will be undefined++ , which is NaN , which will still not work.

This clearly won't work. The solution is to set i to 1 (or whatever value is needed) in the first loop:

 var i = 1; 
+6
source
 jQuery('#'+id+' .tab-pane').each(function(id,t){ var n = jQuery(this).attr('id','pane-'+t); var p_id = n.attr('id'); jQuery('#'+ p_id).find('.nav-tabs li') .eq(id) .find('a') .attr('href', p_id ); } 

You can get rid of i , since id is an increment. And I assume the second selector should use p_id , not id .

+1
source

variable i not assigned undefined

 var i; //undefined jQuery('#'+id+' .tab-pane').each(function(id,t){ var n = jQuery(this).attr('id','pane-'+t); var p_id = n.attr('id'); jQuery('#'+id+' .nav-tabs li:nth-child('+i+') a').attr('href', p_id ); i++; //still undefined }); 
+1
source

Source: https://habr.com/ru/post/1493473/


All Articles