我的代碼中有兩個時間標簽。我必須簡單地在第二次標簽內獲取文本。
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">
uj5u.com熱心網友回復:
沒有getElementByClassName
方法,只有getElementsByClassName
。因此,您必須將代碼更改為.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">
uj5u.com熱心網友回復:
有兩個問題。
首先有一個型別
getElementByClassName
應該是getElementsByClassName
withs
。getElementsByClassName
將回傳HTMLCollection
which isarray-like
,我建議您改用它,querySelector
因為您只想選擇一個元素。
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">
uj5u.com熱心網友回復:
您可以簡單地使用;
const requestedTime=document.querySelector(".entry-date")?.value;
“。” 用于類名,如果您有“example”類,則應將其定義為“.example”
“?” 稱為可選鏈接,這意味著如果沒有類似的物件回傳“未定義”而不是錯誤
".value" 用于獲取值(如果還有一個物件具有相同的類,它將回傳錯誤。)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/508253.html
標籤:javascript html
下一篇:為下拉選單選擇添加占位符照片