Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
284 views
in Technique[技术] by (71.8m points)

javascript - 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 content and iterate through it. can you tell me how to do it, Regex, Jquery, any thing ok,

  1. The content will be in string variable (not in DOM), as IE 9 ignoring quotes from attribute, so i cant use getelementbyclass name,and i followed this answer, to get quotes InnerHTml workAround, now its displaying with quotes. so i need get all the class of ansspans, in an array, so that i'll iterate it n get the text content of each span

    <span id="sss_ctl00_ctl06_lblanswertext">
        assignment 
        <span class="ansspans">submission </span>
        date : &nbsp;10:07:51 AM
    </span>
    

in this eg, expected output will be 1 span object, so that i can iterate over it

Update : I cant use DOm, as we are in quirks mode, so ie 9 will ignore attribute quotes, which i cant traverse using getelement by class name, . so , i need to match all spans in a string variable. hope everyone understood my problem ;(

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

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

(edited to capture inner html instead of whole tag)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.8k users

...