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?

1
  • 3
    $('.myDiv li:nth-child(' + pos +') .myInnerDiv .myInnerMostDiv').attr('id') Commented Oct 30, 2017 at 10:25

2 Answers 2

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; } 
Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

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 caniuse.com/#search=literals

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.