1

Is it possible to transform an element into another element using JavaScript?

For instance, I have:

<p>Début de l'évènement : <time id=event-start></time></p>
<p>Fin de l'évènement : <time id=event-end></time></p>

This is a template that is populated through AJAX, however I need to convert the second time element to span elements in the case that there is no event end time.

The resulting output should be:

<p>Début de l'évènement : <time datetime=2014-09-02T08:00:00 id=event-start>2 septembre 2014 à 8h00</time></p>
<p>Fin de l'évènement : <time datetime=2014-09-02T16:00:00 id=event-end>2 septembre 2014 à 16h00</time></p>

Or:

<p>Début de l'évènement : <time datetime=2014-09-02T08:00:00 id=event-start>2 septembre 2014 à 8h00</time></p>
<p>Fin de l'évènement : <span id=event-end>Indéterminée</span></p>

The JavaScript code that I am using to populate the fields:

function getEventCallback(data) {
    var startEl = document.getElementById('event-start'),
        endEl = document.getElementById('event-end');

    startEl.textContent = moment(data.start).format( ... );
    startEl.setAttribute('datetime', data.start);

    if (data.end) {
        endEl.textContent = moment(data.end).format( ... );
        endEl.setAttribute('datetime', data.end);
    } else {
        endEl.textContent = 'Indéterminée';
        endEl.removeAttribute('datetime');
    }
}

The problem with this is that endEl is still a HTMLTimeElement and does not represent some discrete point in time.

I've looked into the Node interface and it appears that Node.nodeName is immutable, so how do I go about this?

I can't remove the time element completely because subsequent requests might need to use it.

user2864740
  • 60,010
  • 15
  • 145
  • 220
rink.attendant.6
  • 44,500
  • 61
  • 101
  • 156
  • To create a new node, create a new node. – user2864740 Jul 15 '14 at 19:35
  • Consider... "Out with the old, in with the new." – JDB Jul 15 '14 at 19:35
  • I wonder why the duplicate question did not show up in the related questions or while searching. Thanks. – rink.attendant.6 Jul 15 '14 at 19:37
  • You say you want to replace the empty ` – David Thomas Jul 15 '14 at 20:41
  • @DavidThomas If I remove the `time` element and insert a `span` element, how would the next call insert the data at that location in the document? – rink.attendant.6 Jul 16 '14 at 02:45
  • I don't know, yet, because I haven't thought about it. But given your two contradictory requirements I'm unsure as to quite what it is that you want, or need. – David Thomas Jul 16 '14 at 05:23

0 Answers0