John Abel Doe
John Abel Doe

Reputation: 27

Cannot access html element in Javascript

I am trying to access the title of an html div element which is on the page, from a browser extension. When I console log the element in firefox and view it in the dev tools, I get this output:

<div class="X" A="Y" B="Z" C="XX">

When I click the on the above to expand it, I get the list of element characteristics:

...
tagName: "DIV"
textContent: "what is in the text"
title: "what I want to get"

Yet, when I console log element.title I get an empty string. I get undefined when I do element.innerHTML, when there is clearly something there.

Upvotes: 0

Views: 412

Answers (2)

Benoit Chassignol
Benoit Chassignol

Reputation: 289

If you want to access to the title of an htmlElement, it must be set on, on your example it haven't, take a look on mine :

<div class="X" A="Y" B="Z" C="XX" style="styleX" title="myAwesomeTitle">

Upvotes: 0

shrys
shrys

Reputation: 5960

If the element does not have a title attribute it won't log anything. I assume you might be seeing a different div, consider the following:

console.log("class X div title: ", document.getElementsByClassName('X')[0].title);
console.log("class F div title: ", document.getElementsByClassName('F')[0].title);
//jQuery
console.log("class X div title: ", $(".X").prop('title'));
console.log("class F div title: ", $(".F").prop('title'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="X" A="Y" B="Z" C="XX">innerHTML for X</div>
<div class="F" A="Y" B="Z" C="XX" title="target title">innerHTML for F</div>

Upvotes: 1

Related Questions