Get value of data-timestamp attribute - javascript

In my Chrome extension, I'm trying to get info from a page (the value of "data-timestamp": 1490893300813) via a content script, but the result shows 'null'.
//content script:
var tsx = document.getElementsByClassName("date");
var i;
const ts = new Array;
for (i = 0; i < tsx.length; i++) {
var ts[i] = tsx[i].getAttribute("data-timestamp");
console.log("Timestamp" + i + ": " + ts[i]);
}
<!--source code from page:-->
<div class="thread">
<span data-timestamp="1490893300813" class="date">
<span class="absolute">Do, 30.03.2017, 19:01</span>
<span class="relative"></span>
</span>
</div>
I also noticed that the data-timestamp attribute is visible when I show source-code of the page (Ctrl+U) but it isn't visible in DevTools...

You can use document.querySelector('.date') to select the element that has the date class. From there, you can get the element.dataset.timestamp to get the timestamp.
Your code could look something like:
//Get the timestamp as a number ( + is used to convert from a string to a number).
var timestamp = +document.querySelector('.date').dataset.timestamp;
console.log('Timestamp:', timestamp);
//Convert to a Date and display in ISO format for the UTC timezone.
var date = new Date(timestamp);
console.log(date.toISOString());
<div class="thread">
<span data-timestamp="1490893300813" class="date">
<span class="absolute">Do, 30.03.2017, 19:01</span>
<span class="relative"></span>
</span>
</div>

Related

Display <textarea> content in <div>

I'm really new to Javascript. I am trying to output the current date and also the content in the textarea tag in HTML on button click.
However I do not know how to obtain the content when the textarea is not declared along with a name/id/class.
Here's my code:
<script>
function displayPost() {
var thisDiv = document.getElementById("posts");
var date = new Date();
date.classList.add("post-time");
var textarea = document.getElementByTagName("textarea");
textarea.classList.add("post-content");
thisDiv.innerHTML = date + textarea;
}
</script>
<html>
<div id="posts"></div>
<textarea rows="4" cols="60">Type your text here...</textarea>
<button onclick = "displayPost()">Post</button>
</html>
Any sort of help is appreciated! Thank you in advance!
You can use document.querySelector when a dom element does have any name/id/class like:
var textarea = document.querySelector('textarea');
To get the current date in a readable format, you can use toLocaleString() method:
var date = new Date();
console.log(date.toLocaleString());
// → "3/21/2020, 7:00:00 PM"
To get <textarea> current entered value you can use:
var textarea = document.querySelector('textarea');
console.log(textarea.value);
DEMO:
function displayPost() {
var thisDiv = document.getElementById('posts');
var date = new Date();
thisDiv.classList.add("post-time");
var textarea = document.querySelector('textarea');
textarea.classList.add("post-content");
thisDiv.innerHTML = date.toLocaleString() + ': '+ textarea.value;
}
.post-time{padding:20px 0}
<div id="posts"></div>
<textarea rows="4" cols="60" placeholder="Type your text here..."></textarea>
<button onclick="displayPost()">Post</button>
you can make use of document.querySelector() which returns first matching element or document.getElementsByTagName() which returns NodeList of all the textarea elements
var textarea = document.querySelector('textarea').value;
or
var textarea = document.getElementsByTagName('textarea')[0].value;

Adding more and more <timepicker> issue. if one gets changed it changes all of them

I have a little problem, I repeat timepicker with *ngFor, but it's not working properly if I changed the time in one of them, it changes in all. And all have a different id. AN IDEA TO MAKE THE WORk PROPERLY?`
COMPONENT.HTML :
<div id="schedule" *ngFor="let i of Arr(num).fill(1)"
style="display: -webkit-inline-flex">
<timepicker id="timer" class="schedulItem" style="margin-top:-28px"
[(ngModel)]="mytime" [showMeridian]="isMeridian"
[minuteStep]="mstep" (ngModelChange)="changed()">
</timepicker>
<button (click)="addSchedule()"> + </button>
</div>
COMPONENT.TS:
Arr = Array; //Array type captured in a variable
num:number = 1;
mytime: Date;
addSchedule() {
this.num = this.num + 1 ;
var length = document.querySelectorAll('.schedul').length
var time = document.getElementById("timer");
time.id += length;
}
changed(): void {
var time = this.mytime.getHours() + ":" + this.mytime.getMinutes();
console.log(time);
}
I found the problem! the model was the problem [(ngModel)]="mytime". All time pickers to the same model and one gets changed it changes all of them.

Javascript: add integer after second character of string

My CMS is exporting strings into a span element like this:
<span class="starting-hour 0900">0900</span> - <span class="ending-hour 1900">1900</span>
I need the 0900 and 1900 as a class so I can add some CSS to them to fill up a bar. This is working fine, but it also exports it as the starting and ending hour so you see '0900' and '1900' in the frontend. I would like to split these strings up so I can add a ':' after the second integer with Javascript. So in this way the strings would be shown as: '09:00' and '19:00' in the frontend.
My knowledge of Javascript is very basic so I don't know how to get this started. Help would be appreciated.
You could select all elements with on of the classes, then add it like below
document.querySelectorAll('.starting-hour, .ending-hour').forEach(e => {
e.innerText = e.innerText.padStart(4, 0);
e.innerText = e.innerText.substring(0, 2) + ':' + e.innerText.substring(2)
})
<span class="starting-hour 0900">0900</span> - <span class="ending-hour 1900">1900</span>
<span class="starting-hour 0900">900</span> - <span class="ending-hour 1900">1900</span>
Create a reusable function that will return you the hour representation of the values in span:
function getHours(val){
return val.substr(0,2)+':'+val.substr(2,4);
}
var start = document.querySelector('.starting-hour').innerText;
document.querySelector('.starting-hour').innerText = getHours(start);
var end = document.querySelector('.ending-hour').innerText;
document.querySelector('.ending-hour').innerText = getHours(end);
<span class="starting-hour 0900">0900</span> - <span class="ending-hour 1900">1900</span>
But, if you do not have exactly four character long hhhh in your span then use this:
function getHours(val){
return val.substr(0,val.length-2)+':'+val.substr(val.length-2,val.length);
}
var start = document.querySelector('.starting-hour').innerText;
document.querySelector('.starting-hour').innerText = getHours(start);
var end = document.querySelector('.ending-hour').innerText;
document.querySelector('.ending-hour').innerText = getHours(end);
<span class="starting-hour 0900">900</span> - <span class="ending-hour 1900">1000</span>
Taking from Ankit's answer, I made code little dynamic to satisfy both 4 digits and 3 digits time example and added both codes.
function getHours(val){
return val.substr(0,val.length - 2)+':'+val.substr(val.length - 2,val.length);
}
var start = document.querySelector('.starting-hour').innerHTML;
document.querySelector('.starting-hour').innerHTML = getHours(start);
var end = document.querySelector('.ending-hour').innerHTML;
document.querySelector('.ending-hour').innerHTML = getHours(end);
var start = document.querySelector('.starting-hour-two').innerHTML;
document.querySelector('.starting-hour-two').innerHTML = getHours(start);
var end = document.querySelector('.ending-hour-two').innerHTML;
document.querySelector('.ending-hour-two').innerHTML = getHours(end);
<span class="starting-hour 0900">0900</span> - <span class="ending-hour 1900">1900</span>
<br>
<br>
<span class="starting-hour-two 900">900</span> - <span class="ending-hour-two 100">100</span>
function getHours(val){
return val.substr(0,val.length - 2)+':'+val.substr(val.length - 2,val.length);
}
var start = document.querySelector('.starting-hour').innerHTML;
document.querySelector('.starting-hour').innerHTML = getHours(start);
var end = document.querySelector('.ending-hour').innerHTML;
document.querySelector('.ending-hour').innerHTML = getHours(end);
var start = document.querySelector('.starting-hour-two').innerHTML;
document.querySelector('.starting-hour-two').innerHTML = getHours(start);
var end = document.querySelector('.ending-hour-two').innerHTML;
document.querySelector('.ending-hour-two').innerHTML = getHours(end);
<span class="starting-hour 0900">0900</span> - <span class="ending-hour 1900">1900</span>
<span class="starting-hour-two 900">900</span> - <span class="ending-hour-two 100">100</span>
Since yout time is always 4 characters long, it makes it easy to slice the string, put in a : then put them together.
var str1 = "0900".slice(0,2);
var str2 = "0900".slice(2,4);
var time = str1 + ":" + str2;
alert(time);
The addColon function takes an element and sets its innerText to itself, but with the a colon inserted before the last two digits.
Use any method you want to select your span elements and pass them over to addColon. I've gone with a querySelector and a forEach iterator.
const addColon = el => el.innerText = el.innerText.replace(/(\d){2}$/, ":$&");
const timeStamps = document.querySelectorAll("span[class*='-hour']");
timeStamps.forEach(stamp => addColon(stamp));
<span class="starting-hour 0900">0900</span> - <span class="ending-hour 1900">1900</span>

Select elements with data-attribute date value older than current server date

I have a list of events that each have a custom data attribute containing a date:
<ul class="event-list">
<li class="event-item" data-event-date="20150218"></li>
<li class="event-item" data-event-date="20150522"></li>
<li class="event-item" data-event-date="20150928"></li>
</ul>
<ul class="old-event-list">
</ul>
What I'm trying to do is select all of the li.event-item elements within ul.event-list whose data-event-date attribute is older than the current (server time) date, and then move them to ul.old-event-list.
I know i can use appendTo to move the elements, but I have no idea how to select only the elements with an older date attribute than whatever the current server date is.
Any advice is greatly appreciated!
You could iterate over the elements and use the .filter() method to return elements whose data-event-date attribute value is greater/less than a certain value.
Then you would chain the .appendTo() method in order to append the returned elements.
Example Here
$('.event-list .event-item[data-event-date]').filter(function () {
return $(this).data('event-date') > 20150522;
}).appendTo('.old-event-list');
Of course you could dynamically retrieve the current date in JS rather than hardcoding one.
If you could use a date format that the Date object understands then you could rather easily do it like this:
$(function () {
var now = new Date();
var old = $(".old-event-list");
$(".event-list .event-item").each(function () {
var date = new Date($(this).data("event-date"));
if (date < now) {
$(this).appendTo(old);
}
});
});
How to parse a date formatted as 20150522 is a question all its own. It would be much easier to just use a format that Javascript understands, such as 2015-05-22. In PHP it would be date('Y-m-d', $time).
Try
$("[data-event-date^=2015]").map(function(i, el) {
return Number($(el).data("event-date")) > (new Date()).toJSON()
.replace(/[^\d]/g, "").slice(0, 8)
? $(".old-event-list").append(el) : null
});
$("[data-event-date^=2015]").map(function(i, el) {
return Number($(el).data("event-date")) > (new Date()).toJSON().replace(/[^\d]/g, "").slice(0, 8) ? $(".old-event-list").append(el) : null
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<ul class="event-list">
old list
<li class="event-item" data-event-date="20150218">old</li>
<li class="event-item" data-event-date="20150522">new</li>
<li class="event-item" data-event-date="20150928">new</li>
</ul>
<ul class="old-event-list">
new list
</ul>
Try the following code
function pad(number, length) {//small function to pad a number with leading zeros
var str = '' + number;
while (str.length < length) {
str = '0' + str;
}
return str;
}
$('.event-item').each(function() {
var edate = $(this).attr('data-event-date'); // get the value from data-event-date attribute
var fdate = new Date();
var year = fdate.getFullYear();
var month = fdate.getMonth();
var day = fdate.getDate();
var now = year;
if(day<=9) {
now += pad(day,2);
}
if(month<=9) {
now += pad(month,2);
}
if(now>edate) {
$('.old-event-list').html('<li class="event-item">'+$(this).text()+'</li>'); // put the old dates in old eventList
$(this).remove(); // remove item from current list
}
});
FIDDLE
http://jsfiddle.net/8coakc37/1/

Error with JavaScript Object

The code only processes the last string of the object and then proceeds based off of that one and doesn't display a child's name even if their birthday does match today's date when that child's string of data is not the last one entered into the object. I need some advice or help in how to make the javascript find each person whose birthday matches the date and display them instead of just looking at the last child's data
var studentProfile = [];
var index=0;
function saveProfile()
{
studentProfile[index] = {
firstName: document.getElementById("txtFirstName").value,
surname: document.getElementById("txtSurname").value,
birthday: document.getElementById("txtBirthday").value,
contactInfomation: document.getElementById("txtContactInfomation").value,
medicalInformation: document.getElementById("txtMedicalInformation").value,
}
index = index + 1;
localStorage.setItem("students", JSON.stringify(studentProfile));
}
function displayProfile()
{
for (var i = 0; i<studentProfile.length; i++) {
alert("The Student's Name is " + studentProfile[i].firstName + " " + studentProfile[i].surname + ".");
alert("The Student's Birthday is " + studentProfile[i].birthday + ".");
alert("The Student's Contact Information is: " + studentProfile[i].contactInfomation + ".");
alert("The Student's Medical Information is: " + studentProfile[i].medicalInformation) + ".";
}
}
function clearData()
{
document.getElementById("txtFirstName").value = "";
document.getElementById("txtSurname").value = "";
document.getElementById("txtBirthday").value = "";
document.getElementById("txtContactInfomation").value = "";
document.getElementById("txtMedicalInformation").value = "";
}
function birthday()
{
//state all the variables for the program and convert the JSON string from the register js back into an object
var studentProfile = new Object();
var studentBirthday;
var bdayMonth, bdayDay;
var birthDate = new Date();
var today = new Date();
var todayMonth;
var todayDay;
studentProfile = JSON.parse(localStorage.getItem("students"));
// this variable is for the birthday picture to disappear if there are no birthdays, its used later on in the code
var BirthdayBorder = document.getElementById("BirthdayBorder");
// this variable is for the text to change position if there are no birthdays, its used later on in the code
var txtbirthday = document.getElementById("txtContainer");
//I had an alert here to see if the javascript was accurately able to convert the string back into an object and after this is the actual programs code
for (var i = 0; i < studentProfile.length; i++)
{
//here is where the variables regarding the date were specified and extracted from the object that was converted
bdayMonth = studentProfile[i].birthday.substring(0,2);
bdayDay = studentProfile[i].birthday.substring(3,5);
todayMonth = today.getMonth()+1;
todayDay = today.getDate();
//this is where the comparison part of the code starts, basically the birthday entered by the user is compared with today's date
if ((bdayDay == todayDay) && (bdayMonth == todayMonth))
{
//if the dates are equal to one another then the student's firstname is determined and displayed as an output in the html
document.getElementById("birthdays").innerHTML = studentProfile[i].firstName;
BirthdayBorder.style.opacity = "100";
BirthdayBorder.style.marginTop = "0px";
txtbirthday.style.marginTop = "144px";
}
else
{
//the program has determined that there are no birthdays today and will display the text instead of a student's name
document.getElementById("birthdays").innerHTML = "No Birthdays Today! ;)";
//this is the styling part for the birthday border to be transparent and moved to a place where it isn't affecting the website's margins and the text is moved to look better than being in empty space
BirthdayBorder.style.opacity = "0";
BirthdayBorder.style.marginTop = "-1000px";
txtbirthday.style.marginTop = "-50px";
}
}
}
okay here is the requested other information
html:
The Plan
<div id="Titlecont">
<div id="Picture">
<img src="LogoPicture.png" width=60 height=60>
</div>
<div id="Title">
<h1>Little Hands Daycare</h1>
</div>
<div id="Motto">
<p> "It takes a village to raise a child" </p>
</div>
</div>
<div id="Button">
<a href="Computer SciencesWE.html">
<button type="button">
Home
</button>
</a>
<a href="Timer.html">
<button type="button">
Timer
</button>
</a>
<a href="About Us.html">
<button type="button">
About
</button>
</a>
<a href="Register.html">
<button type="button">
Register
</button>
</a>
<a href="Schedule.html">
<button type="button">
Events
</button>
</a>
<button type="button">
Contact
</button>
</div>
</div>
<!--This is where the daily schedule is coded-->
<br>
<div id="Schedule">
<img src="Calender.jpg" width=800 height=540>
<!--This is where the html displays the output of the js-->
<div id="txtContainer">
<p id="birthdays">
.
</p>
</div>
<div id="BirthdayBorder">
<img src="Birthday Border.jpg" width=800 height=600>
</div>
</div>
</body>
</html>
and the requested portion of the javascript has been added to the top of the old code
You have to stop looping when you find a match. Otherwise, you'll process the non-matching items after it, which overwrites the changes you made.
var birthday_found = false;
for (var i = 0; i < studentProfile.length; i++)
{
//here is where the variables regarding the date were specified and extracted from the object that was converted
bdayMonth = studentProfile[i].birthday.substring(0,2);
bdayDay = studentProfile[i].birthday.substring(3,5);
todayMonth = today.getMonth()+1;
todayDay = today.getDate();
//this is where the comparison part of the code starts, basically the birthday entered by the user is compared with today's date
if ((bdayDay == todayDay) && (bdayMonth == todayMonth))
{
//if the dates are equal to one another then the student's firstname is determined and displayed as an output in the html
document.getElementById("birthdays").innerHTML = studentProfile[i].firstName;
BirthdayBorder.style.opacity = "100";
BirthdayBorder.style.marginTop = "0px";
txtbirthday.style.marginTop = "144px";
birthday_found = true;
break;
}
}
if (!birthday_found)
{
//the program has determined that there are no birthdays today and will display the text instead of a student's name
document.getElementById("birthdays").innerHTML = "No Birthdays Today! ;)";
//this is the styling part for the birthday border to be transparent and moved to a place where it isn't affecting the website's margins and the text is moved to look better than being in empty space
BirthdayBorder.style.opacity = "0";
BirthdayBorder.style.marginTop = "-1000px";
txtbirthday.style.marginTop = "-50px";
}

Categories

Resources