Reputation: 296
Is there a way that I can check if an element exists before passing a value into an array with jquery.
For example I have the following code:
hyperlinks = new Array();
$(slideshowThumbs).find('.caption').find('a:first').each(function() {
hyperlinks.push($(this).attr('href'));
});
Which passes and stores the values from a list of items and tells me what their href value is.
The problem that I have at the moment, is that if item 2 in my list does not contain a link, the value that is passed over at position 2 is in actual fact the value from item 3 and not 2.
What I want to do is see if there is an a:first inside of the caption container, and if there isnt pass a value to the array in place that I can subsequently do a check on later. in order to retain the list of items in the array the same as the list of items in my list.
Any ideas?
Many thanks
EDIT: Thanks for your suggestions, though they didn't work straight off, they did get my brain to engage with what I was trying to do - coding with a cold, not always a good combination.
In any case my solution was as follows:
hyperlinks = new Array();
$(slideshowThumbs).find('.caption').each(function() {
var elemExists = $(this).find('a:first');
if (elemExists) {
hyperlinks.push($(this).find('a:first').attr('href'));
}
else {
hyperlinks.push('noLink');
}
});
Thanks again!
Upvotes: 0
Views: 249
Reputation: 1197
Try this.
hyperlinks = new Array();
$(slideshowThumbs).find('.caption').find('a:first').each(function() {
if ($(this).attr('href')) {
// attribute exists
hyperlinks.push($(this).attr('href'));
}
});
Upvotes: 0
Reputation: 12281
I think you're looking for something like this
if ( $(this).attr('href') != '' )
hyperlinks.push($(this).attr('href'));
else
hyperlinks.push("no_link");
Upvotes: 1