Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 667
Yeats Avatar asked Apr 03 '15 16:04

Yeats


People also ask

Why is innerHTML undefined?

InnerHTML returning undefined for <code> tag in HTML Of that collection, your code as it is now is not specifying which member of that collection it wants to use. In that case there is a difference in that it returns a live list. But you would still want to specify which you wanted.

Why innerHTML does not work?

People can struggle and complain about innerHTML not working. Such things usually occur because of human error, when strings are not appropriately defined, or there are some mistakes in JavaScript code.

What does .innerHTML return?

The innerHTML property returns: The text content of the element, including all spacing and inner HTML tags. The innerText property returns: Just the text content of the element and all its children, without CSS hidden text spacing and tags, except <script> and <style> elements.

How do I get innerHTML back?

How it works. First, get the <ul> element with the id menu using the getElementById() method. Second, create a new <li> element and add it to the <ul> element using the createElement() and appendChild() methods. Third, get the HTML of the <ul> element using the innerHTML property of the <ul> element.


2 Answers

It is jQuery - you have to use:

$('.editable-div').html()
like image 172
Legendary Avatar answered Sep 24 '22 19:09

Legendary


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
}
like image 28
josh Avatar answered Sep 24 '22 19:09

josh