# uni.getElementById(id)

返回一个匹配特定 ID 的元素, 如果不存在,返回 null。
如果需要获取指定的节点类型,需要使用 as 进行类型转换。
ID 区分大小写,且应该是唯一的。如果存在多个匹配的元素,则返回第一个匹配的元素。

注意:
本方法获取的元素,是页面栈栈顶的页面的元素,而不是执行本方法代码所在的页面的元素。
因为uni是全局api,只有this.$refs才能和页面绑定。
如果A页面被栈顶的B页面盖住,在A页面执行uni.getElementById会访问到B页面的元素。
除非您确认清楚这个逻辑,否则不建议使用本方法。\

与页面绑定的获取元素的方式是this.$refs获取的对象再进一步as为element。详见

# 参数

名称 类型 必填 默认值 描述
id string.IDString | string - -

3.93+ 支持泛型,可通过 uni.getElementById<ElementType>(id) 获取指定类型的元素。对于组件有自带方法的情况,通过泛型指定具体的元素类型,就可以调用该类型组件的专用方法,比如unicloud-db组件。
具体的组件元素类型,可查阅组件文档/组件类型获取。

	<template>
		<view>
			<text id='text' ref='textRef'>test text</text>
		</view>
	</template>
	<script>
		export default {
      onReady(){
        uni.navigateTo({
          url: '/pages/test/test'
          success() {
            // 通过 ref 获取指定页面的元素
            const textRef = this.$refs['textRef']
            // 通过 getElementById 获取指定页面的元素,此时当前页面为 test 页面,所以获取不到 #text 元素
            const textNode = uni.getElementById('text')
          }
        })
      }
		}
	</script>

# 返回值

类型 必备
UniElement | null

# 示例

hello uni-app x

Template

Script

<template>
  <page-head id="page-head" title="getElementById"></page-head>
  <view class="uni-padding-wrap">
    <text id="text">this is text</text>
    <view id="view" class="uni-common-mt" style="border: 1px solid red">this is view</view>
    <button class="uni-btn" @click="changePageHeadBackgroundColor">
      修改 page-head 背景色
    </button>
    <button class="uni-btn" @click="changeTextColor">
      修改 text 字体颜色
    </button>
    <button class="uni-btn" @click="changeViewStyle">
      修改 view 宽高及背景色
    </button>
    <button class="uni-btn" @click="goMultipleRootNode">
      跳转多根节点示例
    </button>
  </view>
</template>



# getElementById 兼容性

Android iOS web
3.91 4.11 4.0

# 参见

相关 Bug

# 通用类型

# GeneralCallbackResult

名称 类型 必备 默认值 描述
errMsg string - 错误信息