if $('.item:last').attr('id').split('-')[1]
is not undefined
var liid
equals that, and if it is undefined
then it equals null
views:
157answers:
7assuming that .item:last is defined:
var liid = typeof $('.item:last').attr('id').split('-')[1] != undefined ? $('.item:last').attr('id').split('-')[1] : null;
otherwise:
var liid = $('.item:last').length > 0 ? $('.item:last').attr('id').split('-')[1] : null;
Michael Mrozek is correct. You wouldn't want to do the entire lookup twice.
Just do
var liid = (typeof($('.item:last').attr('id').split('-')[1]);
liid = typeof(liid) == 'undefined' ? null : liid;
or do the if statement.
var liid=$('.item:last').attr('id').split('-')[1];
liid?'':liid=null;
This will only work however if $('.item:last').attr('id').split('-')[1] when not undefined equals something other than the values that equal false such as 0
or an empty string ''
;
var value = $('.item:last').attr('id').split('-')1;
(value == undefined) ? liid = value : liid = null;
The operator is called a ternary conditional operator, or, sometimes referred to as the ternary operator. Info on undefined, null, etc. is here.
Also, I stored $('.item:last').attr('id').split('-')1
in a variable so that the next time I wanted to get that value, the machine wouldn't have to recalculate it by calling multiple functions; a simple read from memory would be enough.
var liid = $('.item:last').attr('id').split('-')[1] || null;
This In JavaScript the logical-or (||
) operator works differently than you might be used to. ||
will return the its left operand if it's something "truth-y". A truth-y value is one of the following:
- An object
- Any number != 0
true
- A non-empty string
var parts= $('.item').last().attr('id').split('-');
var liid= parts.length>=1? parts[1] : null;
avoid
:last
and the other jQuery-specific non-standard selectors when you can, as they will cause the relatively slow ‘Sizzle’ selector engine to be used instead of the fast browser in-builtquerySelectorAll
method on modern browsers. Use jQuery navigation functions instead in preference.whilst you can use
|| null
as in the previous answers to get a shorter expression, this has caveats that may or may not affect you. Personally I prefer to be explicit about what test I'm doing.In particular, the empty string would also be ‘falsy’ and so would cause the
null
value to be returned if theid
happened to bea--b
.
If what your question is asking is how to write this in ‘JavaScript’, ie. without jQuery:
var els= document.getElementsByClassName('item');
var parts= els[els.length-1].id.split('-');
...
however this uses the HTML5 getElementsByClassName
method, which not all browsers support yet, so you'd have to add in fallback support for that (see previous questions on this subject).