Get value inside Div Javascript

Viewed 7213

ho,

I have a div that I access like so:

 var gridcellrowvalue0 = gridcell0.innerHTML;

This returns to me the following div:

 <div class="DivOverflowNoWrap Ellipsis" style="width:100%;" data-textwidth="50" data-originaltext="DefaultText" data-ingrid="1">DefaultText</div>

In my JS I would like to accesss the "DefaultText" variable and I have tried this:

 gridcellrowvalue0.innerHTML;
 gridcellrowvalue0.getAttribute("data-originaltext");

But none of them work. I'm assuming that getAttribute doesn't work because it is not really an element, it's innerhtml.

My goal is to use the "DefaultText" value in an IF-statement and therefore I simply need it.

I appreciate any pointers, my friends!

5 Answers

You could access your element directly from gridcell0 using gridcell0.querySelector('.DivOverflowNoWrap') instead, like :

var gridcell0 = document.querySelector('#x');
console.log( gridcell0.querySelector('.DivOverflowNoWrap').innerHTML );

Snippet:

var gridcell0 = document.querySelector('#x');

if (gridcell0.querySelector('.DivOverflowNoWrap') !== null) {
  console.log(gridcell0.querySelector('.DivOverflowNoWrap').innerHTML);
} else {
  console.log('Does not exist');
}
<div id="x">
  <div class="DivOverflowNoWrap Ellipsis" style="width:100%;" data-textwidth="50" data-originaltext="DefaultText" data-ingrid="1">DefaultText</div>
</div>

With Javascript also it can be achieved but I am showing here using jQuery

$('document').ready(function() {
  var div = $(".DivOverflowNoWrap");
  var text = div.text();

  alert(text);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="DivOverflowNoWrap Ellipsis" style="width:100%;" data-textwidth="50" data-originaltext="DefaultText" data-ingrid="1">DefaultText</div>

The problem is how you access the div in the first place. If you do it like you described (with gridcell0.innerHTML). It will return a string. Not an HTML element.

Therefore you can't use .getAttribute or .innerHTML, because you try to apply it on a string. Access your div differently (querySelector or getElementBy...) and you will be able to use those.

You can use jquery:

$("[class='DivOverflowNoWrap']").text();


$("[class='DivOverflowNoWrap']").attr("data-originaltext")
Related