Yeats
Yeats

Reputation: 2065

Why is innerHTML returning 'undefined'?

I'm trying to catch the "value" inside this div, which is editable:

<div class="editable-div" contentEditable="true">Hey</div>

I figured I could do this simply via JavaScript:

var changedText = $('.editable-div').innerHtml

However, this variable will always return "undefined", which confuses me.

Can someone enlighten me on how to reach this "value"?

Upvotes: 17

Views: 33834

Answers (4)

Legendary
Legendary

Reputation: 2242

It is jQuery - you have to use:

$('.editable-div').html()

Upvotes: 38

josh
josh

Reputation: 10318

A jQuery wrapped object is actually not the raw DOM node, but essentially an array of raw DOM nodes that can be acted upon with jQuery specific methods, such as .html(). If you want to interact with the DOM node, you can retrieve it by either iterating through the list or getting the element of that list if you know which one it is:

$('div').each(function(index, element) {
  element.innerHTML // ...
}

$('div').get(0).innerHTML
$('div')[0].innerHTML

Note that while it is "kind of" like an array, in that you can get DOM nodes using the array syntax of $('div')[0], you can't treat it like an array in Javascript. In other words, you can't do this:

$('div').forEach(function(element) {
  element.innerHTML
}

Upvotes: 3

Titi Wangsa bin Damhore
Titi Wangsa bin Damhore

Reputation: 7199

innerHtml is DOM. try $('.editable-div')[0].innerHtml

Upvotes: 0

Code Lღver
Code Lღver

Reputation: 15603

innerHtml is used with javascript selector and you are using jQuery. so replace innerHtml with .html() or .text() function.

Use this:

var changedText = $('.editable-div').html();

Upvotes: 1

Related Questions