Why is innerHTML returning 'undefined'? - javascript

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

It is jQuery - you have to use:
$('.editable-div').html()

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
}

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();

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

Related

textContent returns undefined

I have a table in which I want to extract the text of the active item. I do this with the following code:
var addedWorkout = $("#custDropDownMenuA").find(".dropdown-item.active");
console.log(addedWorkout);
addedWorkout = addedWorkout.textContent;
console.log(addedWorkout);
The problem is that I keep getting undefined. I checked the console and it indeed finds the element I want without fail.
I am relatively new to Javascript, but after over an hour of Googling I could not find the issue and I don't understand why. I know that I can get the text element if I hardcore it using the following line:
document.querySelector("#selectiona1").textContent
but not with:
$("#selectiona1").textContent
What is the difference between these 2? I read that textContent is part of the DOM, to my understanding it relates to objects and according to my console i think it is an object. I made some crazy attempts like putting the object I got into the querySelector, but nothing works.
With this line:
var addedWorkout = $("#custDropDownMenuA").find(".dropdown-item.active");
you're using jQuery to select the .dropdown-item.active inside #custDropDownMenuA, and when you select with jQuery, you get a jQuery object in response. So, addedWorkout is a jQuery object, and jQuery objects generally do not have the same properties/methods as standard HTMLElements. (querySelector is the vanilla Javascript method to retrieve an element)
Either select the [0]th item in the jQuery collection to get to the first matching element:
var addedWorkout = $("#custDropDownMenuA").find(".dropdown-item.active")[0];
Or use the jQuery method to get the text of the first matching element, which is .text():
var addedWorkoutText = addedWorkout.text();
(note the use of a new variable - you will likely find it easier to read and debug code when you create new variables rather than reassigning old ones, when possible)
Your var 'addedWorkout' is a Jquery object, not a html element.
To show the text use:
addedWorkout.text();
Alternatively, you can change the 'addedWorkout' to a html element by adding the index [0], like this:
addedWorkout[0].textContent;

Javascript: Remove Child when using document.write

I want to have something like this:
var abc1 = document.write('<html>HTMLPAGECONTENTHERE</html>');
function removepage(){
abc1.parentNode.removeChild(abc1);
}
removepage();
That won't work; document.write doesn't return anything.
You should use the DOM APIs instead (createElement() and appendChild()), or, more easily, jQuery.
document.write inserts a stream of HTML directly into the page. It has no useful return value.
If you want to manipulate what it outputs via DOM, then you have to have a known quantity to match with getElementById, getElementsByTagName or some other method for getting HTML Element Nodes from a DOM.

Javascript DOM Document createElement from tag source

Is there a way to create a new element in a Document object from the tag source? Essentially what I'd like to do is something to effect of:
myDocument.createElement('<sometag attr="lol">');
No, native DOM API for .createElement doesn't support that syntax. You need to create the plain Element and set any property either directly on the object
newElem.attr = "lol";
or (better), use .setAttribute()
newElem.setAttribute( 'attr', 'lol' );
What you "could" do is do create a documentFragment, then use .innerHTML to write that string into that fragment and finally .append its contents to its target destination.
well, use innerHTML instead of trying to hack dom manipulation for this kind of thing.
To do so, create a valid node with dom if you want (or get it via getElementById), then set innerHTML of this node with your code
The innerHTML property works here - but it's a tad bit difficult to place the thing where you want it sometimes. For example:
var div = document.createElement('div');
div.innerHTML = "<img src='http://www.google.com/logos/classicplus.png'/>";
In my humble opinion, it's a heck of a lot easier to use jQuery to handle it for you, as it comes with all of the jQuery methods already attached.
var div = $("<div class='blah'><img src='http://www.google.com/logos/classicplus.png'/></div>");
div.find('img').hide();
div.appendTo('body');
div.find('img').fadeIn();

JQuery select by ID vs document.GetElementByID

I'm just starting with JQuery and am working through a tutorial vid. At one point the presenters go for javascript instead of a JQuery selector. Just wondering why the javascript getElementById below works fine when passing an object to a function, but the second one doesn't?
Thanks!
// works
addTask(document.getElementById('taskText'), evt);
// doesn't
addTask($('#taskText'), evt);
getElementById() returns a DOM element reference.
jQuery's selector returns a jQuery object. You can get the element reference from the jQuery object using
$('#taskText').get(0);
See http://api.jquery.com/get/
To add to the other answer, regarding the result, if you want to use jQuery (which is easier to read), you can get the dom node directly like so:
addTask($('#taskText')[0], evt);
$('#taskText') returns a jQuery object reference.
document.getElementById('taskText') returns a DOM element reference.
If your addTask() function doesn't know how to convert them to what it needs, then that would be the issue since one of them will need a conversion.
If you want to get the first DOM element reference from the jQuery object, you can do so with this:
$('#taskText').get(0)
So these two should be identical:
$('#taskText').get(0)
document.getElementById('taskText')
Both are not exactly same
document.getElementById('taskText'); //returns a HTML DOM Object
var contents = $('#taskText'); //returns a jQuery Object
var contents = $('#taskText')[0]; //returns a HTML DOM Object
so you have to change it to get HTML Dom Object
addTask($('#taskText')[0], evt);
As #Phil and #jfriend00 have pointed out, document.getElementById('taskText') is a DOM element, and $('#taskText') is a jQuery object. The latter is an object of all DOM elements that match the selector.
Think of it as a zero based array, you could pass in the DOM element by doing this:
addTask($('#taskText')[0], evt);

Creating Javascript object from JQuery object

Currently I'm unit testing the following code:
if ($(selectedElement).innerText == 'blah')
{
// do something
}
with selectedElement being an anchor object selected from the UI.
In my test code, I have created a DOM structure which has that anchor in the proper position ready to be selected. The problem here is that since selectedElement is originally a javascript object, I need to convert the anchor I got from the DOM structure (which is a JQuery object) in order to get into the above condition.
I have tried the following, with no success:
// DOM structure using HtmlDoc
/*:DOC += <span id='testSpan' class='testSpanClass'><a href='#' id='selectedElem'>blah</a></span> */
selectedElement = $('#selectedElem')[0];
My goal is to be able to use a normal Javascript object to satisfy the condition, and also be able to switch it back to a jQuery object to satisfy conditions further down the function. But if there is a better approach I'll give it a go.
Does anyone have any ideas on how to go about this problem?
EDIT: Is there a solution that does not require changing of the code? selectedElement is actually a global variable.
Thanks.
I am not sure what browser you are testing in, but innerText is an IE only property. Since you are already using jQuery, I would suggest you just call the .text() method on the selected element like this:
selectedElement = $('#selectedElem')[0]; // Get DOM element
if ($(selectedElement).text() == 'blah')
{
// do something
}
You're method of getting the DOM object is fine: $('#selectedElem')[0] or $('#selectedElem').get(0) are equivalent, but the first one is faster in large loops.
jQuery's get method returns the original DOM elements for that jQuery object.
I think perhaps you need to use $('#selectedElem').get(0)
can you use jquery's .html() ?
if ($(selectedElement).html() == 'blah')
{
// do something
}
otherwise, without changing code:
var selectedElement = $('#selectedElem')[0];
if (selectedElement.innerHTML == 'blah')
{
// do something
}

Categories

Resources