Irtza.QC
Irtza.QC

Reputation: 1136

Get HTML element via aria label

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>

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?

Upvotes: 65

Views: 137510

Answers (3)

Buzinas
Buzinas

Reputation: 11725

Probably you're trying to get the Element before it's even loaded on the page.

If so, you can wrap your code into the DOMContentLoaded event:

document.addEventListener('DOMContentLoaded', function() {
  console.log(document.getElementById(':ik').textContent);
});

But if you really want to get the element by its aria label, you can do that:

document.querySelector('div[aria-label="Message Body"]');

But this way is much less performatic, and you'll need to do exactly what I've mentioned above too.

Upvotes: 18

Rana Ahmer Yasin
Rana Ahmer Yasin

Reputation: 537

this is the permenent solution check it it will work forever

var getElementsByAttribute = function (attr, value) {
var match = [];

var elements = document.getElementsByTagName("*");

for (var ii = 0, ln = elements.length; ii < ln; ii++) {

if (elements[ii].hasAttribute(attr)) {

  /* If a value was passed, make sure it matches the element's */
  if (value) {

    if (elements[ii].getAttribute(attr) === value) {
      match.push(elements[ii]);
    }
    } else {

    match.push(elements[ii]);
  }
}
 }
  return match;
};

(function () {
  var baz = getElementsByAttribute('data-foo', 'bar');
  for (var xx = 0, ln = baz.length; xx < ln; xx++) {
    baz[xx].innerHTML = 'These *are* the droids we are looking for!';
 }
})();

Upvotes: -6

T.J. Crowder
T.J. Crowder

Reputation: 1075009

querySelector or querySelectorAll with an attribute selector should do it:

// 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"]');

Or if that ID is stable, simply:

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

(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"

(A little) more in this answer, which references this Google documentation.

Upvotes: 117

Related Questions