Skip to content Skip to sidebar Skip to footer

How To Get All Spans In String Variable, With Particular Class Name

as i am getting tough time to list out all spans, which having class='ansspans', may be one or more span with 'ansspans' classes will be there, i need to get all the spans with its

Solution 1:

(as been said on this site before, sometimes it's ok to parse a limited, known set of xml with regex)

   //assumes no <spanid="stupid>"class="ansspans">, and no embedded span.ansspans
        var data = ' <spanid="sss_ctl00_ctl06_lblanswertext"> assignment    \n date : &nbsp;10:07:51 AM    \n     <spanclass="ansspans">ONE has a new \n line in it</span><spanclass="ansspans">TWO</span><spanclass="ansspans">3 </span><spanclass="ansspans">4 </span><spanclass="ansspans">5 </span>';
        var myregexp = /<span[^>]+?class="ansspans".*?>([\s\S]*?)<\/span>/g;
        var match = myregexp.exec(data);
        var result = "spans found:\n";
        while (match != null) {
            result +=  "match:"+RegExp.$1 + ',\n';
            match = myregexp.exec(data);
        }
        alert(result);

(edited to capture inner html instead of whole tag)

Solution 2:

The following jQuery selector $('span.ansspans') will get all the <span class="anspans"> for the page.

If you need something for a specific element, add a prefix of the appropriate selector, i.e. $('#sss_ctl00_ctl06_lblanswertext span.ansspans')

If this needs to be done in a more dynamic way - look into functions like find(), filter(), etc.

Solution 3:

solution using jquery

var tempArray = $("span.ansspans");//this will select all the span elements having class 'ansspans' and return them in an arrayvarlen = tempArray.length;//calculate the length of the arrayfor(var index = 0;index<len;index++){
    var reqString = $(tempArray[index]).html();
}

These string values can be either put inside an array or can be utilised then and there only.

If you want textContent, use .text() instead of .html()

Post a Comment for "How To Get All Spans In String Variable, With Particular Class Name"