0

My code is below

<script>
ball1 = "this is ball1";
ball2 = "this is ball2";
ball3 = "this is ball3";
bat = "this is not a ball";

var arr = $("[name^='ball']");
alert(arr.length);
</script>

I want to get all the variables starting with the string 'ball'. How do I do it? The above code gives the arr.length as 0. Is my code correct?

sam
  • 11
  • 3
  • they are javascript variables... not html objects with the name attribute that starts with ball – Adween Mar 05 '14 at 21:02
  • 1
    Can I ask why you are doing this? – Toby Allen Mar 05 '14 at 21:05
  • 1
    @Adween so how do I find javascript variables? – sam Mar 05 '14 at 21:05
  • @sam try procrastinator's method – Adween Mar 05 '14 at 21:11
  • I've read [your previous question](http://stackoverflow.com/q/22157209/1636522) and it makes things a bit more clear. Two questions remain though : which variables do you want to access - globally or locally defined variables - and *why*? I believe the *why* is important here to know how to answer properly. –  Mar 05 '14 at 21:31
  • I've read all of your previous questions, now I wonder whether your problem has something to do with the following one : http://stackoverflow.com/q/19526456/1636522. Let me know. –  Mar 05 '14 at 21:49
  • @procrastinator I have explained in a new question as it was difficult to explain here in comments. http://stackoverflow.com/questions/22228756/accessing-custom-defined-variable-object-in-javascript-in-for-in-loop – sam Mar 06 '14 at 16:41

3 Answers3

2

jQuery is intended to query the DOM tree. Anyway, try this :

var r = /^ball/,
    balls = [];
for (var k in window) {
    r.test(k) && balls.push(window[k]);
}

Notice that window (uppermost scope) is implicitely populated :

<script>
var ball1 = '1'; // global variable
window.ball1; // '1'
</script>

However, this is not true if you're working inside of a function :

function f() { 
    var ball1 = '1'; // local variable
    window.ball1; // undefined
}
f();
window.ball1; // undefined;

In this case, there no way to access ball1 from the outside.

0

That will give 0 as

$("[name^='ball']") will search the DOM with attribute 'name' not Variable name

Makrand
  • 587
  • 5
  • 14
0

As an alternative to procrastinator's elegant javascript solution. If you wanted to do it using jquery and dom objects you could do something similar to this

http://jsfiddle.net/kDy8Z/1/

<span name="newsletter"></span>
<span name="milkman"></span>
<span name="newsboy"></span>

<script>
$(function(){
    var array = $("[name^='news']");
    alert(array.length);
});
</script>

They dont have to be spans but anything with the name attribute that starts with news.

Example taken from here https://api.jquery.com/attribute-starts-with-selector/

Adween
  • 2,792
  • 2
  • 18
  • 20