通过aria标签获取HTML元素 [英] Get HTML element via aria label

查看:196
本文介绍了通过aria标签获取HTML元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在做一个小的chrome扩展,为此,我需要从DOM中获取一个div进行操作.我得到了DOM,但是在获取必需的div时遇到了麻烦.这是它的代码.

I'm making a small chrome extension and for it I need to grab a div from the DOM to manipulate. I get the DOM but I'm having trouble grabbing the required div. Here's the code for it.

<div id=":ik" class="Am Al editable LW-avf" hidefocus="true" aria-label="Message Body" g_editable="true" role="textbox" contenteditable="true" tabindex="1" style="direction: ltr; min-height: 137px;"><br></div>

我尝试了getElemenyByIDdocument.attrib,但是都返回了null.关于如何获取将在此div中输入的文本的值的任何建议吗?

I've tried getElemenyByID, and document.attrib but both return null. Any advice on how to get the value of the text that will be input inside this div?

推荐答案

querySelectorquerySelectorAll应该做到这一点:

// The first element that matches (or null if none do):
var element = document.querySelector('[aria-label="Message Body"]');
// A list of matching elements (empty if none do):
var list = document.querySelectorAll('[aria-label="Message Body"]');

或者该ID是稳定的,只需:

Or if that ID is stable, simply:

var element = document.getElementById(":ik");

(请注意,d是小写字母;在示例中,您使用大写字母.)

(Note that the d is lower case; you have it in upper case in your example.)

无论哪种方式,都可以通过在清单中包含以下代码来确保代码在页面加载之前不会运行:

Either way, make sure your code doesn't run until the page is loaded, by including this in your manifest:

"run_at": "document_end"

此答案(其中引用了 查看全文

登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆