janicehoplin janicehoplin - 1 year ago 42
Javascript Question

I cannot get pure text from a div with javascript or jquery

So I have a div with text like this:

<div id="myDiv">Get this text</div>

I have tried the following methods:

var $var2 = $('#myDiv').text();

var div = document.getElementById('myDiv');
var $var2 = div.textContent; // white space/block around text
var $var2 = div.innerHTML; // same as textContent

I think I've tried others but that's what I can remember at the moment.

I've also seen this answer, but I'm not sure if it is necessary/applies to my case.

.clone() //clone the element
.children() //select all the children
.remove() //remove all the children
.end() //again go back to selected element
.text(); //get the text of element

I'm sending two variables in a
call and
is always blank unless I specify directly something like
$var2 = "text";

When I alert the two variables say $var1 and $var2 side by side, $var2 is pushed away form $var1 unless I declare
$var2 = "text";
in which case they are side by side. Then the insert goes through,
is not blank.

I'm thinking I may just use a hidden input field and set the value of that with this div label so that my insert can still go through.

Answer Source

the text selected is not pure text, there's space around it, and isn't accepted by insert into MySQL database with PHP. This variable is blank

Trim the whitespaces using

var value = $.trim( $("#myDiv").text() );


In JS ES5 you can use String.prototype.trim()

var value = document.getElementById("myDiv").textContent.trim();