Reading all div spaces dynamically

I have a div inside that has a number of spans. Now I want to read all the text of all the gaps along with the identifier thrir and fill it in the javascript map, where key = spanid and value = "text span.How can I do this?

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

How can I fill out the card?

+6
javascript html
source share
3 answers

You can get the elements using document.getElementById and document.getElementsByTagName , then iterate over them and add to the object. Use textContent and innerText to get the text of the span element and paste them into the object as follows:

 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 how it works here: http://www.jsfiddle.net/SJs4h/

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

Using jQuery is 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: No 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]; } 
-2
source share

All Articles