Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
231 views
in Technique[技术] by (71.8m points)

html - Javascript to get text node of td using tr class

I have the following codes below:

<table>
  ...
[Multiple lines ommited for brevity]

<tr class="bibItemsEntry"> 
<td width="31%" ><!-- field 1 -->&nbsp;Archives, Thesis Col. Graduate, 12F (Mezz.) Henry Sy Sr. Hall 
</td>
<td width="46%" ><!-- field C -->&nbsp;<a href="/search~S1?/cCDTG006829/ccdtg006829/-3,-1,,E/browse">CDTG006829</a> <!-- field v --><!-- field # -->&nbsp;<!-- field ! -->&nbsp;ROOM USE ONLY</td>
<td width="23%" ><!-- field % -->&nbsp;CHECK SHELF </td></tr>
</table>

<p id="demo">Test</p>

What I wanted to do is to use javascript and get the first value of the text node of <td> under <tr class="bibItemsHeader">. I'm trying to put the value into <p id="demo">. I'm trying out the below javascript code:

var x = document.getElementsByClassName("bibItemsEntry");
document.getElementById("demo").innerHTML = x[0].innerHTML;

But I'm getting all the td text node values. Can somebody help with my problem? Thanks in advance!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You are selecting the tr element and not the first td that you really want. Try this:

const td = document.querySelector('.bibItemsEntry td:first-child');
const p = document.getElementById('demo');
p.innerHTML = td.textContent;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...