How can i get text inside time tag using Pure Javascript?

Viewed 45

I have a two time tags in my code . I have to simply get text inside second time tag.

var children=document.getElementByClassName("entry-date published").textContent;
document.write(children);
<time class="updated" datetime="2022-09-14T00:54:04+05:30" itemprop="dateModified">14th September 2022</time>
<time class="entry-date published" datetime="2022-02-09T18:35:52+05:30" itemprop="datePublished">9th February 2022</time></span> <span class="byline">

4 Answers

Simply you can use;

const requestedTime=document.querySelector(".entry-date")?.value;

"." uses for class names, if you have "example" class you should define it as ".example"

"?" called as Optional chaining that means if there is no object like that return "undefined" not an error

".value" uses for getting value (if there is one more object has same class it'll return error.)

There is no getElementByClassName method, only getElementsByClassName. So you would have to change your code to .getElementsByClassName(...)[0].

var children=document.getElementsByClassName("entry-date published")[0].textContent
console.log(children);
<time class="updated" datetime="2022-09-14T00:54:04+05:30" itemprop="dateModified">14th September 2022</time>
<time class="entry-date published" datetime="2022-02-09T18:35:52+05:30" itemprop="datePublished">9th February 2022</time></span> <span class="byline">

There are two issues.

  1. First there is a type in getElementByClassName it should be getElementsByClassName with s.

  2. getElementsByClassName will return HTMLCollection which is array-like, I suggest you to use querySelector instead because you want to select just one element.

var text = document.querySelector(".entry-date.published").textContent;
alert(text)
<time class="updated" datetime="2022-09-14T00:54:04+05:30" itemprop="dateModified">14th September 2022</time>
<time class="entry-date published" datetime="2022-02-09T18:35:52+05:30" itemprop="datePublished">9th February 2022</time></span> <span class="byline">

To get a 2nd child, you can use :nth-child(2). So your code would be something like this:

document.write(document.querySelector("time:nth-child(2)").textContent);

Learn more about CSS selectors on CSS Diner

Related