Dan Rubio Dan Rubio - 1 month ago 6
CSS Question

Why am I unable to find an html element through jQuery/JS string interoplation?

I have a series of div blocks each with a unique numerical id.

For example:
enter image description here

As part of a project I'm working on, I want to select the 29th element after the element I choose. So if I chose the first div with id of

1
then I want to be able to choose div with id
30
. Here is how I am attempting to do this with the first div:

let int = parseInt($('.blockattribute').first().attr('id')) + 29;
$('#' + toString(int);


This gives me the following error:

Uncaught Error: Syntax error, unrecognized expression: #[object Undefined]


This should work though. By executing
$('#30');
, I'm able to select the div I want. What could be the problem?

Answer

You're using Object.prototype.toString which would return [object Undefined] when you do

Object.toString(30);

you wanted to use Number.prototype.toString() instead, and you'd do that like so

let int = parseInt($('.blockattribute').first().attr('id')) + 29;
$('#' + int.toString());

but you really don't need it, as concatenating a string and a number returns a string anyway