Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
290 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 Reply

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)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...