-2

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">

1
  • 1
    And what's your question about this? What exactly is not working with the given code? What do you mean by "get text inside second time tag"?
    – Nico Haase
    Commented Sep 15, 2022 at 6:37

4 Answers 4

3

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

2
  • 1
    Please add some explanation to your answer such that others can learn from it
    – Nico Haase
    Commented Sep 15, 2022 at 6:38
  • 1
    Yo, thank you for the ?. part! I code in JS like a year or two, but I haven't seen such a thing! Very useful!
    – Plantt
    Commented Sep 15, 2022 at 9:08
0

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">

0

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">

0

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.