Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

reading all spans of a div dynamically

I have a div inside which i have number of spans. Now i want to read all text of all spans along with thrir id and populate it into a javascript map where key = spanid and value =" text of span.How can i do it?

Eg <div mydiv="xyx" >   
     <span id ="sp1" > M/span>
     <span id ="sp2" > M/span>
     .... 
      ..

   </div>

How can i populate the map?

like image 925
akshay Avatar asked Feb 07 '11 07:02

akshay


People also ask

Can CSS be applied to span?

The <span> tag is easily styled by CSS or manipulated with JavaScript using the class or id attribute.


2 Answers

You can get the elements using document.getElementById and document.getElementsByTagName, then iterate through them and add them to the object. Use textContent and innerText to obtain the text of the span element, and insert them into the object like so:

var spans = document.getElementById('xyx').getElementsByTagName('span'), 
    obj = {};

for(var i = 0, l = spans.length; i < l; i++){
    obj[spans[i].id] = spans[i].textContent || spans[i].innerText;
}

See it working here: http://www.jsfiddle.net/SJs4h/

like image 93
Yi Jiang Avatar answered Oct 13 '22 23:10

Yi Jiang


var container=document.getElementById('xyx');
var spanArray=container.getElementsByTagName('span');
for(var s=0;s<spanArray.length;s++){
  spanText=spanArray[s].innerHTML;
}
like image 41
derekcohen Avatar answered Oct 14 '22 00:10

derekcohen