简体   繁体   中英

javascript - How can I get a div that is inside of a div?

<div class="message cid-524f7e6b28946"><i class="icon icon-chat-manager"></i>
<div class="timestamp" style="display: block;">4:44pm</div><span class="from staff clickable">SamueI </span><span class="text">&nbsp;.</span>

I want to get the div "timestamp"

I want to change the timestamp text like this, but it comes up with "null"

 document.getElementById("timestamp").textContent = "new text";

You might want to use the querySelector like:

document.querySelector('.timestamp').textContent = "new text";

Fiddle

Or otherwise you need to use ID instead of Class in your element, like:

<div id="timestamp" style="display: block;">4:44pm</div> 

Modify your code to be

<div class="message cid-524f7e6b28946"><i class="icon icon-chat-manager"></i>
<div id="timestamp" style="display: block;">4:44pm</div><span class="from staff clickable">SamueI </span><span class="text">&nbsp;.</span>

and

document.getElementById("timestamp").textContent = "new text";

will work.

You are using getElementById even though timestamp is a class name. Change it to id="timestamp"

由于IE9还提供了getElementsByClassName,因此执行以下操作非常安全:

document.getElementsByClassName('timestamp')[0].textContent = "new text";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM