0

Having trouble getting the id of divs on my page that begin with "refresh".

Example: I have 3 divs on my page.

<div id='refresh5'></div>
<div id='refresh12'></div>
<div id='red'></div>

I'm trying to create a array using javascript of the divs that begin with "refresh", tried using the following:

var arr = $('div[id^="refresh"]');
alert(arr);

But the alert only shows me [object Object], instead of the div id's ????

Any help is appreciated.

2
  • 1
    You can try console.log(arr) to see the contents of the object. The reason you get back an object is because jQuery will returns a jquery object. Someone else can probably explain it better. Commented Mar 7, 2012 at 23:38
  • You might want to use a debugger (I suggest chrome or firefox's developer tools) and set a breakpoint instead of using alerts for debugging purposes.. Commented Mar 7, 2012 at 23:39

5 Answers 5

2

The problem you're having is that the selector you've supplied returns an array of jQuery objects, not a list of ids.

Try instead:

var arr = $('div[id^="refresh"]').map(function(){ return this.id;}).get().join(',');
alert(arr);​

JS Fiddle demo.

References:

Sign up to request clarification or add additional context in comments.

Comments

1

If you do this for testing purposes, use console.log instead of alert. You can look at all the details ni the javascript log (hit F12 in IE or right click the page and select "Inspect element" in chrome/safari)

Comments

1

jQuery object (result of $()) is not Array or String. It's object.

Comments

1

I think you use jquery there. $() returns an "array-like-object", so the output you get is absolutely correct there!

Comments

0

I dont know if the selector is right cause I didnt check it, but when it is, you will get the id's like this:

//your code here...
var a = [];
arr.each(function() {
   a.push($(this).attr('id'));
});

alert(a);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.