I am trying to add one to a variable, but is not working. Why is this?
var numElementsDisplay = "5";
$('.searchdropdown .element:nth-child(n+' + numElementsDisplay + 1 + ')').attr('style', $(this).attr('style') + '; ' + 'display: none !important');
I am trying to add one to a variable, but is not working. Why is this?
var numElementsDisplay = "5";
$('.searchdropdown .element:nth-child(n+' + numElementsDisplay + 1 + ')').attr('style', $(this).attr('style') + '; ' + 'display: none !important');
You need to use () wrap wrap the numeric operation, else a string concatenation will be performed
var numElementsDisplay = "5";
$('.searchdropdown .element:nth-child(n+' + (+numElementsDisplay + 1) + ')').attr('style', $(this).attr('style') + '; ' + 'display: none !important');
Also don't know why you want to use !important, but if you want to append the display rule to the existing set of inlined rules you will have to use a callback, else this will not refer to the current element
$('.searchdropdown .element:nth-child(n+' + (+numElementsDisplay + 1) + ')').attr('style', function () {
//also will have to use a callback
return $(this).attr('style') + '; ' + 'display: none !important'
});
But if you wan tot use !important a better solution will be is to use a class like
$('.searchdropdown .element:nth-child(n+' + (+numElementsDisplay + 1) + ')').addClass('hidden');
then
.hidden {
display: none !important
}
numElementsDisplay is a string, so parentheses don't help.var numElementsDisplay = "5"; as a string, declare it as a numer to make it work var numElementsDisplay = 5; another solution is to use an unary plus to convert the string to a number like (+numElementsDisplay + 1)Here you are:
$('.searchdropdown .element:nth-child(' + (Number(n) + Number(numElementsDisplay) + 1) + ')').attr(...)
I don't know what is the var n in this context.
Hope this helps.
n isn't a Javascript variable, it's part of the css. The literal text n+ needs to be in the final string.You've assigned the string "5" to numElementsDisplay change it to
var numElementsDisplay = 5;
and all will be fine
I am unclear as to whether you want numElementsDisplay to be an integer (ex. 5 + 1 = 6) or a string (numElementsDisplay + 1 =numElementsDisplay1). If you want the first case, then you need to do use:
parseInt(numElementsDisplay + 1) .
Otherwise you should probably have the 1 in quotes, as: (numElementsDisplay + "1").