The issue is because you never update the content of the element after working with the content. Also note that you don’t need to use replace()
. Try this:
let el = document.getElementById("date");
if (el) {
el.textContent = el.textContent.substring(0, 10);
}
<div class="Wrapper shadow">
<h3 class="date" id="date">2020-02-20T14:39:40Z</h3>
</div>
That being said, you’re just getting the first 10 characters of the date string, which is not infallible. If the locale changes your code will break. To fix this you can create a Date object from the string and output the format you require explicitly:
let el = document.getElementById("date");
if (el) {
let date = new Date(el.textContent);
let year = date.getFullYear();
let month = ("00" + (date.getMonth() + 1)).slice(-2);
let day = ("00" + date.getDate()).slice(-2);
el.textContent = `${year}-${month}-${day}`;
}
<div class="Wrapper shadow">
<h3 class="date" id="date">2020-02-20T14:39:40Z</h3>
</div>
You can also use Moment.js for format the date you need.
const el = document.querySelector('#date');
const myDateFormat = 'YYYY-MM-DD';
const date = el.textContent;
const newDate = moment(date, myDateFormat).format(myDateFormat);
el.textContent = newDate;
<script src="https://momentjs.com/downloads/moment.min.js"></script>
<div class="Wrapper shadow">
<h3 class="date" id="date">2020-02-20T14:39:40Z</h3>
</div>
Hope to help you and others ^^.
my problem is the following . Im using Duda widget Builder to build my own Widgets. In one application there is a Date and by default its depicted as ISO .
Now converting that isnt too hard, I tried the following :
if (document.getElementById("date") !== null) {
let date = document.getElementById("date").toString();
let dater = date.substring(0, 10);
document.getElementById("date").innerHTML.replace(date, dater);
console.log('Test');
}
<div class="Wrapper shadow">
<h3 class="date" id="date">2020-02-20T14:39:40Z</h3>
</div>
Now it doesnt throw any errors and it console.logs the “Test”. But the date stays in ISO.
The widget works with jQuery I believe it has something to do with that.
The widget interface where you write down the javascript is encapsulated by this: function(element,data,api){ ‘my js code from above’}
Please help.
I dont understand . Its all the HTML code I have .
The full HTML Output is very long and I cant show it to you . But maybe you can tell me for what to look ?
Yes it works like a charme ! Thank you, you are a Saint ! I will have to look into the dynamic of jQuery….
Ok thank you Rory. I will implement this. Maybe help the others too ^^