Reputation: 67
I'm newbie to the Javascript/Jquery world. I have a div with several links and i want to collect the url's .
Then i want to extract from those href's the last 9 characters (actually i wish to optimize it and collect the digits independently the length at the end of each string).I tried to extract them with the slice()
method but it does not work.
In console the error is
Object doesn't support property or method 'slice'
Can i convert the object to a string ? Your help is appreciated ! The code is the following
$(document).ready(function(){
var $posts= $('a.entry_title').each(function(){
$(this).attr('href');
});
var posts1 = $posts[0].slice(-9);
var posts2 = $posts[1].slice(-9);
var posts = ["MyURL"+ posts1,"MyURL"+posts2]
$('#div1').load(posts[0] + " .shadow3");
$('#div2').load(posts[1] + " .shadow3");
});
</script>
Upvotes: 0
Views: 5467
Reputation: 33618
You see Object doesn't support because $.each returns a jQuery object.
Use .map() instead because it returns an array on which slice would work
var $posts= $('a.entry_title').map(function(){
return $(this).attr('href');
});
Result would be
["link1", "link2", "link3"....] // just a sample
If you wish to get an array of hrefs with last nine characters of each link you can use map this way
var $posts= $('a.entry_title').map(function(){
return $(this).attr('href').slice(-9); // or you can do your own magic
});
Result would look like this
["k1", "k2", "k3"....] // after slicing the words
Upvotes: 4
Reputation: 736
Try next one:
var hrefs = []; // list of collected and sliced hrefs.
var $posts= $('a.entry_title').each(function() {
// slice & push each href into list.
hrefs.push($(this).attr('href').slice(-9));
});
console.log('href list:', hrefs); // control result.
var posts = ["MyURL"+ hrefs[0],"MyURL"+hrefs[1]]
Upvotes: 0