简体   繁体   中英

JavaScript, Tampermonkeys - how to make an array out of strings in an HTML element?

I want to convert the names of months into numbers and store the month in a table's cell on a webpage. I figured having it as an array would let me refer to the month names by their array numbers and I could insert table tags before and after them. I got as far as replacing the month names:

var dates = document.getElementsByClassName("date");
    for(var i = 0, l = dates.length; i < l; i++)
    {
        var date = dates[i];
        date.innerHTML = date.innerHTML.replace('Aug', '08');
    }

The relevant html segment looks like

<span class="date">Mon&nbsp;2017.&nbsp;Aug&nbsp;28&nbsp;15:25:13</span>

which I'd like to turn into

<span class="date"><table><tbody><tr><td>Mon&nbsp;</td><td>2017.&nbsp;08&nbsp;28&nbsp;15:25:13</td></tr></tbody></table></span>

if you can use "& nbsp;" as split "Character", try something like this.

 var dates = document.getElementsByClassName("date"); for(var i = 0, l = dates.length; i < l; i++) { var table = document.createElement("table"); var tbody = document.createElement("tbody") var tr = document.createElement("tr"); var date = dates[i]; var string = date.innerHTML.replace('Aug', '08.'); var split = string.split("&nbsp;"); for(var j = 0; j < split.length; j++){ var td = document.createElement("td"); td.appendChild(document.createTextNode(split[j])); tr.appendChild(td); } date.innerHTML=""; tbody.appendChild(tr); table.appendChild(tbody); date.appendChild(table); } 
 <span class="date">Mon&nbsp;2017.&nbsp;Aug&nbsp;28&nbsp;15:25:13</span> 

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