0

I am trying to pass a variable inside a method of js so that I can get some value as return, example

  getId: function (pos) {
    var myVar = $('.myDiv li:nth-child(pos) .myInnerDiv .myInnerMostDiv').attr('id');
    return myVar;
  }

And then call this as

this.getId(6); //where 6 is the pos

However this seems to be not working.

What am I doing wrong here?

Hello Universe
  • 3,248
  • 7
  • 50
  • 86

2 Answers2

3

you are writing pos directly in the string, so it is taken as is... What you want is concatenate its value instead!

getId: function (pos) {
    var myVar = $('.myDiv li:nth-child('+pos+') .myInnerDiv .myInnerMostDiv').attr('id');
    return myVar;
  }
Salketer
  • 14,263
  • 2
  • 30
  • 58
2

Try to change this:

var myVar = $('.myDiv li:nth-child(pos) .myInnerDiv .myInnerMostDiv').attr('id');

To:

var myVar = $(`.myDiv li:nth-child(${pos}) .myInnerDiv .myInnerMostDiv`).attr('id');

It concatenates pos into the string by using ES6's template litteral

Faly
  • 13,291
  • 2
  • 19
  • 37
  • what you use here is called string interpolation and its part of ECMAscript6 and may not work on every browsers right now. surely you can use BABEL to trans-pile it to the plain js. you can see the browser support at http://www.caniuse.com/#search=literals – M.R.Safari Oct 30 '17 at 10:30