获取内部文本 + alt 如果有 img
我有一个跨度,就像
<span class="message">blablabla <img src="smileys/saute.gif" alt="SAUTE"></span>
我想获得文本 +图像的alt一样,如果
我尝试过:
let el = document.getElementById(".message");
console.log(el.innerText)
但是它仅返回文本,我想要img的文本 + alt(好像我们在浏览器上使用鼠标复制粘贴)
谢谢
i have a span like
<span class="message">blablabla <img src="smileys/saute.gif" alt="SAUTE"></span>
i want to get the text + the alt of image if are there
I have tried :
let el = document.getElementById(".message");
console.log(el.innerText)
but it return just the text, i want text + alt of img (as if we copy paste with the mouse on a browser)
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果您想在访问
span
和img
标签的内容之前检查其是否存在,请使用以下代码:If you want to check for the presence of the
span
andimg
tags before accessing their content, here's the code for it:不要使用
getElementById
。您需要querySelector
使用 CSS 选择器来选取具有消息类的元素。然后在该元素上再次使用
querySelector
来查找图像,并记录alt
属性。Don't use
getElementById
. You wantquerySelector
to use a CSS selector to pick up the element with the message class.Then use
querySelector
again on that element to find the image, and log thealt
attribute.首先,span 元素没有任何 ID,它有一个类,因此您可以通过 querySelector 定位它:
document.querySelector('.message')
请注意,querySelector 返回它找到的第一个元素,querySelectorAll 返回找到的元素的数组。
然后,您可以使用找到的元素并转到
firstElementChild
/ 或使用children[0]
(子元素的索引)。您甚至可以使用:
document.querySelector('.message > img')
来定位图像。First of all the span element does not have any ID, it has a class so you can target it via querySelector:
document.querySelector('.message')
Note that querySelector returns the first element it finds, querySelectorAll returns an array of found elements.
Then you can use the element you found and go the the
firstElementChild
/ or usechildren[0]
(the index of the child).You can even use:
document.querySelector('.message > img')
to target the image.你可以尝试这样:-
You can try this way :-