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

Time:09-15

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  datetime="2022-09-14T00:54:04 05:30" itemprop="dateModified">14th September 2022</time>
<time  datetime="2022-02-09T18:35:52 05:30" itemprop="datePublished">9th February 2022</time></span> <span >

CodePudding user response:

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.)

CodePudding user response:

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  datetime="2022-09-14T00:54:04 05:30" itemprop="dateModified">14th September 2022</time>
<time  datetime="2022-02-09T18:35:52 05:30" itemprop="datePublished">9th February 2022</time></span> <span >

CodePudding user response:

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  datetime="2022-09-14T00:54:04 05:30" itemprop="dateModified">14th September 2022</time>
<time  datetime="2022-02-09T18:35:52 05:30" itemprop="datePublished">9th February 2022</time></span> <span >

CodePudding user response:

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