开发者

reading all spans of a div dynamically

开发者 https://www.devze.com 2023-02-08 18:41 出处:网络
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 mapwhere key = spanid and value =\" text of span.How ca

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?


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/


var container=document.getElementById('xyx');
var spanArray=container.getElementsByTagName('span');
for(var s=0;s<spanArray.length;s++){
  spanText=spanArray[s].innerHTML;
}


Using Jquery its very simple:

var spans = $('#xyx').find('span');
var arr = new Array();
 foreach(spans as span)
 {
       arr[$(span).attr('id')] = $(span).text;
 } 

Hope i helped.

Update: None jquery way:

var spans = document.getElementById('xyx');
spans = spans.getElementsByTagName('span');
var arr = new Array();
foreach(spans as span) 
{
   arr[span.getAttribute('id')] = arr[span.innerHTML];
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号