S. A. Malik
S. A. Malik

Reputation: 3655

Javascript Split Function and Jquery not working together

The Get variables of the URL need to be parsed. I have made a jQuery object of document.location and then have used the attr function to get the search attribute to get all the variables. But when i use the split function on it and after that each() is used it gives error stating that the object does not have a method each .

TypeError: Object [object Array] has no method 'each'  

Code is :

 $(document.location).attr('search').split('&').each()

I have also tried to use the search property in the first function but it does not allow it i.e $(document.location.search) gives error.

I have also checked that data type of the what is returned by split function, the console says that it is an object, i am also confused that it should have been an array.

P.S : all the above code goes in document.ready function of jQuery

Upvotes: 5

Views: 1360

Answers (4)

palaѕн
palaѕн

Reputation: 73896

Try this:

$.each($(document.location).attr('search').split('&'), function (index, value) {
    alert(index + ': ' + value);
});

jQuery .each() method is used to iterate over a jQuery object, executing a function for each matched element.

But what you get from the $(document.location).attr('search').split('&') is a JavaScript array, which obviously has no method 'each': that is why you are getting the error.

To loop through an array in jQuery you need to use $.each() method like above.

Upvotes: 5

Vince
Vince

Reputation: 1527

As far as I know, JS-arrays don't have a each()-function.

Try

var search_arr = $(document.location).attr('search').split('&');
for (var s in search_arr) {
    console.log(search_arr[s];
}

instead.

Upvotes: 0

Guffa
Guffa

Reputation: 700252

Making a jQuery object from the document.location object is pointless, because it's not a DOM element.

Just get the search property from the object, and use the $.each method intead of .each as you are looping an array, not elements:

$.each(document.location.search.split('&'), function(){
  ...
});

Upvotes: 7

DiMono
DiMono

Reputation: 3368

jQuery's each() function is meant to be called on its own, directly from jQuery; javascript arrays don't have it as a function, because it wasn't built that way.

I think you're looking for this:

$.each($(document.location).attr('search').split('&'), function (index, value) {
    // stuff
});

Upvotes: -1

Related Questions