简体   繁体   中英

How do I get all spans created in my HTML page using jQuery

I'm getting all input texts in my HTML page by using this:

 var inputs = data.context.find(':input');
 $('#result').text(JSON.stringify(inputs.serializeArray()));

Then I have an JSON string with id and value of each input text.

I'm trying to do something similar but with all my spans. I have this in my HTML file:

 <td class="name"><span>{%=file.name%}</span></td>

I can have as many <td class="name"> ... tags as I want. So I have to get the value of all of them and convert to an JSON string as I did with the input text above.

How can I do it?

this code snippet: $('.name span') will return an array of objects, so in order to get the text from each one you need to run on it as an array:

$('.name span').each(function(index,val){
   //do something with val
});

you can see a reference to this method here .

Simple fiddle: http://jsfiddle.net/CMdBa/1/

Iterate over .name (or specifiy deeper if necessary), build your data structure (using data ), and then convert it to JSON. Working example: http://jsfiddle.net/tLuPC/

Below is simulating id if you needed to obtain that as mentioned in your post. Using data- attribute to store info. Otherwise you can simply just obtain the name .

var data = [],
    jsonData = null;

$('.name').each(function () {
    var item = $(this);

    data.push({
        id: item.data('id'),
        name: $('span', item).text()
    });
});

jsonData = JSON.stringify(data);

console.log(JSON.stringify(jsonData));

You can use a map function to enumerate and format a collection.

var spanTextArray = $('td.name span').map(function(){
    return $.trim(this.innerHTML);
}).get();

This will output an array of file names, you could easily modify the return to output an array of key value pairs.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM