Manipulate HTML with jQuery
I'm trying to style some HTML, generated from Google Calendar, it's something I don't have control off. It's plain simple HTML.
This is what I have:
    <li><a><span class="data">Wh开发者_Go百科en: gio 27 gen 2011<br /><br />Where: XXXX<br />Event state: confirmed</span></a></li>
<li><a><span class="data">When: gio 20 gen 2011<br /><br />Where: XXXX<br />Event state: confirmed</span></a></li> 
This is what I'm trying to get:
<li>
    <a>
        <span class="when">When:</span>
        <span class="day">gio</span>
        <span class="number">27</span>
        <span class="month">gen</span>
    </a>    
</li>
<li>
    <a>
        <span class="when">When:</span>
        <span class="day">gio</span>
        <span class="number">20</span>
        <span class="month">gen</span>
    </a>    
</li>
With this messy code:
$(function(){
    var words = $('div.data').text().split(" ");    
    $("div.data").html("<span>" + words + "</span>");
    $("div.data span:first").addClass("when");  
});
And this is what I get:
   <li>
    <a title="" class="tip">
        <div class="data">
            <span class="when">
                <a xmlns="http://www.w3.org/1999/xhtml">when:,gio,27,gen,2011
where:,XXX,XXX
Event,state:,confirmedWhen:,gio,20,gen,2011
where:,XXX,XXX
Event,sate:,confirmed
                </a>
            </span>
        </div>
    </a>    
</li>
As you can see I have this new <a> element (why?) and both <li> texts are inside the same <span>. Twice (to be honest, the second doesn't have the "when" class). This should not be hard to do. It's just too hard for me.
$(function(){
    var words = $('div.data').text().split(" ");    
    $("div.data").html("<span class='when'>" + words[0] + "</span>");
    $("div.data").append("<span class='day'>" + words[1] + "</span>");
    //...etc
});
You can try this:
$('span.data').each(function() {
  var text = $(this).text();
  text = text.substr(0, text.indexOf("Where")); //remove stuff from "Where:"
  var words = text.split(" ");
  var parent = $(this).parent();
  $(this).remove();
  var classes = ["when", "day", "number", "month", "year"];
  for (var i = 0; i < words.length; i++) {
    parent.append($("<span />").addClass(classes[i]).text(words[i]));
  }
});
 
         加载中,请稍侯......
 加载中,请稍侯......
      
精彩评论