You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用JavaScript检测video标签内是否存在source子标签

实现方法

方法1:直接查询子元素(最简洁)

通过querySelector直接查找video标签下的source元素,返回值非空即存在:

const video = document.getElementById('video-upload-preview');
// 仅匹配直接子source标签可改成 querySelector(':scope > source')
const hasSource = !!video.querySelector('source');

if (hasSource) {
  // 存在source标签的逻辑
} else {
  // 不存在source标签的逻辑
}

方法2:遍历子元素判断

如果需要自定义匹配规则,可以遍历video的子元素过滤判断:

const video = document.getElementById('video-upload-preview');
const hasSource = Array.from(video.children).some(item => item.tagName.toLowerCase() === 'source');

动态监听方案

如果需要实时感知source标签的增删变化,可以使用MutationObserver监听:

const video = document.getElementById('video-upload-preview');
const observer = new MutationObserver(() => {
  const hasSource = !!video.querySelector('source');
  // 状态变化后的业务逻辑
  console.log('source标签是否存在:', hasSource);
});
// 配置监听子节点变化
observer.observe(video, { childList: true });

// 不需要监听时记得销毁,避免内存泄漏
// observer.disconnect()

内容的提问来源于stack exchange,提问作者Sara Ree

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 23:27:02