AbuMariam
AbuMariam

Reputation: 3708

Javascript : How to get multiple span elements by ID?

I have several span elements which begin with the same id as shown below...

<span id="graph_machine" 
<span id="graph_human" 
<span id="graph_custom" 

I would like to access these 3 Span elements as an array in my Javascript function..

var elems = document.getElementsById("graph*");

But getElementsById does not support returning multiple values. Any suggestions? Perhaps using a different function and some wildcard?

Thanks.

Upvotes: 1

Views: 1820

Answers (5)

SomeShinyObject
SomeShinyObject

Reputation: 7821

You could get all spans and then check each ID individually:

var spans = document.getElementsByTagName("span");
var graphSpans = [];
for (var i = 0; i < spans.length; i++) {
    if (spans[i].id.substring(0,5) === "graph") {
        graphSpans.push(spans[i]);
    }
}

http://jsfiddle.net/Sp6sp/

Upvotes: 0

wael34218
wael34218

Reputation: 4950

If you are using jQuery you can use $( "span[id^='graph_']" )

Upvotes: 0

James Allardice
James Allardice

Reputation: 166071

Use document.querySelectorAll:

var elems = document.querySelectorAll("[id^=graph]");

That will return a node list of any element with an id attribute whose value starts with "graph".

Upvotes: 9

Karthick Kumar
Karthick Kumar

Reputation: 2361

try this with jquery

$("span").each(function(){
console.log($(this).attr('id'));
});

Demo
http://jsfiddle.net/p5k2a/1/

Upvotes: -2

codesnooker
codesnooker

Reputation: 1181

Try to get all span ID and then check if span ID starts with "graph"

var spans = document.getElementsByTagName("span");
var graphSpans = new Array();
for (var i = 0; i <= spans.length; i++) {
   if (spans.id.startsWith("graph")) {
      graphSpans.push(spans[i]);
   }
}

Since startsWith method is not available in Javascript, so you need to add it to prototype as soon document is ready.

jQuery(document).ready(function() {
if (typeof String.prototype.startsWith != 'function') {
     // see below for better implementation!
        String.prototype.startsWith = function (str){
            return this.indexOf(str) == 0;
        };
    }
}

Upvotes: 0

Related Questions