get the text content from a contenteditable div through javascript - javascript

I want retrieve the text content from a contentEditable div through javascript. What are the options of doing this? I've tried innerHTML but it doesn't work.

Why not use textContent for this:
var contenteditable = document.querySelector('[contenteditable]'),
text = contenteditable.textContent;
http://jsfiddle.net/E4W8y/1/

Unfortunately, I've found that innerText is the only way to preserve newlines in contenteditable dom nodes. What I'm doing (tested only in chrome at the moment) is this:
var innerText = editableDiv.innerText // using innerText here because it preserves newlines
if(innerText[innerText.length-1] === '\n')
innerText = innerText.slice(0,-1) // get rid of weird extra newline
return innerText

lblMailContent is the id of editable field.
var details= document.getElementById("lblMailContent").innerHTML;
Put this code in clientClick. It worked well for me.

use jQuery and do
var content = $('#my-contenteditable-div').html();
also look up these links:
http://west-wind.com/Weblog/posts/778165.aspx
Extracting text from a contentEditable div

I solved it this way, because i need html-input:
message = $('<div>').html(
$('#area').html()
.replace(/<(div|p|br)[^<]*?>/g, '<br />')
.replace(/<([(i|a|b|u)^>]+)>(.*?)<\/\1>/gim,
function(v) { return '' + escape(v) + ''; })
).text();
Allows the tags A, B, I, U and replaces Divs and Ps with BRs

Using text content, working fine in most of the cases
Working Example: jsfiddle(verified in Safari)

Use this:
function textFromDiv(selector) {
const element = document.querySelector(selector);
const text = element.html().replace(/<div>/g,"\n").replace(/<\/div>/g,"").replace(/<br>/g,"\n");
return text;
}```

Here's my spin at it...
input = document.getElementsByTagName("div")[0];
input.onkeyup = function(){
text = "";
for(i=0; i<input.childNodes.length; i++){
text += input.childNodes[i].textContent + "\n";
}
text = text.trim();
console.log(text);
}

Vanilla JS solution
html:
<div
contenteditable="true"
onkeyup="myFunction(this, event)"
></div>
js:
function myFunction(self, event){
console.log(self.innerText)
console.log(event)
}

Related

Javascript - How can I replace text in HTML with text in script

I am new to javascript. I was thinking getelementbyid but i don't know how to make it work
Like the title, here is what I mean
For example I have in HTML:
<p>fw_93</p>
<p>fw_94</p>
<p>fw_93</p>
So what I want is to make script to replace those fw_93 fw_94 to what I want.
For example
Instead of displaying "fw_93" I want it to display "9.3". Same with fw_94 to 9.4
Replace fw_ with nothing, divide the number by 10:
Array.prototype.forEach.call(document.getElementsByTagName('p'), function(el) {
el.innerHTML = parseInt(el.innerHTML.replace(/[A-Za-z_]*/, '')) / 10;
});
<p>fw_93</p>
<p>fw_94</p>
<p>fw_93</p>
Okay so select the tags.
Loop over the collection
read the html
match the string
replace the html
var ps = document.querySelectorAll("p");
for (var i=0; i<ps.length; i++) {
var p = ps[i];
var txt = p.innerHTML; //.textContent
var updated = txt.replace(/.+(\d)(\d)/, "$1.$2");
p.innerHTML = updated;
}
<p>fw_93</p>
<p>fw_94</p>
<p>fw_93</p>
Using JQuery
Not sure why I did it with JQuery, guess I wasn't paying enough attention. No point in me re-writing as there are already good answers in JS. Though I will leave this in case it's of use to anyone that is using JQuery.
You can loop though each <p> element and covert the contents, something like this:
$("p").each(function() {
var text = $(this).html();
var text = text.substring(text.indexOf("_") + 1);
var text = text[0] + "." + text.substring(1);
$(this).html(text);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>fw_93</p>
<p>fw_94</p>
<p>fw_93</p>
You may need to add validation depending on how reliable your input is.
Note that the code makes the following assumptions:
There will always be a _ followed by at least 2 digits
The . will always go after the first digit
Your HTML:
<p id="p1">init_value</p>
Your JS:
document.getElementById("p1").innerHTML = "new_value";

Insert <span> in <p> element

I got like;
<p>Variable Text</p>
And I want to it to be;
<p>Variable <span>Text</span></p>
Is this possible by a javascript function? / or jQuery.
Oh yeah, and the p-element got an ID and the text inside the p-element is variable but always consists of 2 words. I want a span around the last word of the text by a javascript function.
Try this
var txt = "Hello bye";
var dataArr = txt.split(' ');
var paragraph = document.getElementById("pid");
paragraph.innerHTML = dataArr[0]+ " <span>"+dataArr[1]+"</span>";
Here is a demo
It's possible (the following assumes the p has an ID, like you said), in it's simplest form you can just do:
var paragraph = document.getElementById("pId");
paragraph.innerHTML = "Hello <span>World</span>";
Or if you want to use jQuery:
$("#pId").html("Hello <span>World</span>");
Or (as you said in comments, you want to keep the existing content, but wrap the last word in a span, you can do:
var newHTML = $("#pId").html().replace(" ", " <span>");
$("#pId").html(newHTML).append("</span>");
DEMO
I would like to share a jQuery solution, which is regardless of any words defined in your p element
$("p").html(function(){
var mystring= $(this).text().split(" ");
var lastword = mystring.pop();
return mystring.join(" ")+ (mystring.length > 0 ? " <span>"+ lastword + "</span>" : lastword);
});
Demo
In the demo above, I am splitting the string first, than am using pop to get the last index in the array, and than am adding span element and returning the string using join
$("document").ready(function(){
$("p").append("<span>world</span>");
});
With JQuery append
$("#paragraphId").append('<span>Text in span</span>');
jQuery is easier, and personally I think it's better to use than only javascript:
jQuery:
$("#paragraphID").append("<span>World</span>");
HTML:
<p id="paragraphID">Hello</p>

How to filter out HTML tags from within a div tag using JavaScript

I have this HTML code:
<div>
756
<span></span>
</div>
Using JavaScript I want to retrieve the number 756 from within the div tag and increment it by 1. What is the best method of filtering out the <span> from within the div tags so I get only the number?
Try this:
var div = document.getElementsByTagName("div")[0],
content = div.textContent || div.innerText;
textContent is supported by all browsers except IE8- and innerText is supported in all browsers except FF4-. So using both, you should get a stable result.
http://www.quirksmode.org/dom/w3c_html.html
Both properties return the text content with stripped HTML tags.
Example: http://jsfiddle.net/HnWxk/ (tested in chrome/ff/ie7)
Now, if you want to increment it, just do:
content++;
It should cast a Number: http://jsfiddle.net/HnWxk/3/
You can use .innerText to do so.
var div = document.getElementsByTagName("div")[0];
var inner;
if(div.innerText) {
inner = div.innerText;
} else {
inner = div.textContent;
}
var number = parseInt(inner);
number++;
alert(number);
Fiddle.
<div id="mydiv">
756
<span></span>
</div>
<script>
var textNode = document.getElementById("mydiv").childNodes[0];
var number = parseInt(textNode.nodeValue);
textNode.nodeValue= number + 1;
</script>​
DEMO
Just an other way to do it without the browser incompatibility of innerText and textContent. I use innerHTML after I use a regular expression to extract the number, Also it is recommended to always define the radix when you use parseInt (will simply avoid some weird surprise I let you discover) and finally incrementing the value.
var theNum = parseInt(document.getElementById('someDiv').innerHTML.match(/\d+/), 10);
alert(theNum+=1)
The best solution would be to wrap the number in its own <span>.
If that is not possible (you don't create the HTML code), you can iterate over all child nodes of the <div>. One of them will be the text node you want to target.
<div id="number">
756
<span></span>
</div>​
d = document.getElementById("number")
n = parseInt(d.innerHTML)+1;
alert(n)​;​
Assuming this html code:
<div id="someDiv">
756
<span></span>
</div>
You can use this (with jquery):
var div = $("#someDiv");
div.text(parseInt(div.text()) + 1);
I used split on the text to get the number.
Also used jQuery to get the text, you can use the other methods people used here.
var divText = $('div').text();
var contentArray = divText.split('\n');
var yay = parseInt(contentArray[1].trim(), 10);
alert(yay);
alert(yay++);
See fiddle here.
The best way would be wrap the number in an element, but you can workaround with this:
var div = document.getElementById('div')
var num = parseInt((div.innerText) ? div.innerText : div.textContent);
div.childNodes[0].nodeValue = num + 1;

How to get div text also with it's input's values

I was wondering how to obtain the text inside a given div, with also the input's values as text.
<div id="example">This is a <input type="text" value="right"/> test.</div>
If I just try to get text like this with jQuery :
$("#example").text();
The result would be This is a test. and I'd want : This is a right test.
The number of input would be unknow. As well as the order of the elements...
EDIT :
I finally resolved my own problem :
var finalText="";
$("#example").contents().filter(function() {
if(this.nodeType==3){ finalText =finalText+ this.nodeValue;}
else if(this.nodeName=="INPUT"){ finalText=finalText+this.value;}
return finalText
})
The living example
But #Jonathan Lonowski answer is more clear and simpler than mine !
Here is a quick plugin that will do this for you:
$(document).ready(function() {
$.fn.extend({
getContentText: function() {
var t = '';
this.contents().each(function(i,c) {
var method = $(c).is("input") ? "val" : "text";
t += $(c)[method]();
});
return t;
}
});
alert($("#example").getContentText());
});
Try it out here:
http://jsfiddle.net/wQpHM/
You might try cloning so you can replaceWith the inputs with their values. Then grab the text as you were:
var clone = $('#example').clone();
clone.find(':input').replaceWith(function () {
return $(this).val();
});
alert(clone.text());
You can loop though all children of the <div> and replace then with their values. Something like this:
$.fn.allText = function(){
var $this = this.clone();
$this.children().each(function(){
$(this, $this).replaceWith(this.value);
});
return $this.text();
};
alert($('#example').allText());
Demo: http://jsfiddle.net/4mGmH/
get html and strip html tags
$('#example')[0].innerHTML.replace(/(<([^>]+)>)/ig, '').replace(/(\s+)/g, ' ')
Using innerText
document.getElementbyId('example').innerText;
To get HTML tags:-
document.getElementbyId('example').innerHTML;
Refer this URL element.innerHTML

How to get the HTML for a DOM element in javascript

Imagine I have the following HTML:
<div><span><b>This is in bold</b></span></div>
I want to get the HTML for the div, including the div itself. Element.innerHTML only returns:
<span>...</span>
Any ideas? Thanks
Use outerHTML:
var el = document.getElementById( 'foo' );
alert( el.outerHTML );
Expanding on jldupont's answer, you could create a wrapping element on the fly:
var target = document.getElementById('myElement');
var wrap = document.createElement('div');
wrap.appendChild(target.cloneNode(true));
alert(wrap.innerHTML);
I am cloning the element to avoid having to remove and reinsert the element in the actual document. This might be expensive if the element you wish to print has a very large tree below it, though.
First, put on element that wraps the div in question, put an id attribute on the element and then use getElementById on it: once you've got the lement, just do 'e.innerHTML` to retrieve the HTML.
<div><span><b>This is in bold</b></span></div>
=>
<div id="wrap"><div><span><b>This is in bold</b></span></div></div>
and then:
var e=document.getElementById("wrap");
var content=e.innerHTML;
Note that outerHTML is not cross-browser compatible.
old question but for newcomers that come around :
document.querySelector('div').outerHTML
You'll want something like this for it to be cross browser.
function OuterHTML(element) {
var container = document.createElement("div");
container.appendChild(element.cloneNode(true));
return container.innerHTML;
}
If you want a lighter footprint, but a longer script, get the elements innerHTML and only create and clone the empty parent-
function getHTML(who,lines){
if(!who || !who.tagName) return '';
var txt, ax, str, el= document.createElement('div');
el.appendChild(who.cloneNode(false));
txt= el.innerHTML;
ax= txt.indexOf('>')+1;
str= txt.substring(0, ax)+who.innerHTML+ txt.substring(ax);
el= null;
return lines? str.replace(/> *</g,'>\n<'): str;
//easier to read if elements are separated
}
var x = $('#container').get(0).outerHTML;
as outerHTML is IE only, use this function:
function getOuterHtml(node) {
var parent = node.parentNode;
var element = document.createElement(parent.tagName);
element.appendChild(node);
var html = element.innerHTML;
parent.appendChild(node);
return html;
}
creates a bogus empty element of the type parent and uses innerHTML on it and then reattaches the element back into the normal dom
define function outerHTML based on support for element.outerHTML:
var temp_container = document.createElement("div"); // empty div not added to DOM
if (temp_container.outerHTML){
var outerHTML = function(el){return el.outerHTML||el.nodeValue} // e.g. textnodes do not have outerHTML
} else { // when .outerHTML is not supported
var outerHTML = function(el){
var clone = el.cloneNode(true);
temp_container.appendChild(clone);
outerhtml = temp_container.innerHTML;
temp_container.removeChild(clone);
return outerhtml;
};
};
var el = document.getElementById('foo');
el.parentNode.innerHTML;

Categories