I want to use execcommand 'formatblock' for select a line by 'p' tag or span with specific class or Id or any css style in my contenteditable div(own rich text editor). i searched a lot for this, but i could not find anything which valuable for me.
document.execCommand('formatblock', false, 'p');
How can i add class or id or css in this code?
If you want to add id or class for CSS in content editable div, then you will use below code---
<script>
function CssFnctn()
{
document.execCommand('formatblock', false, 'p')
var listId = window.getSelection().focusNode.parentNode;
$(listId).addClass("oder2");
}
</script>
.oder2
{
padding-left: 3em;
}
There are many ways to do it. Just use execCommand 'insertHTML' instead to replace selected text with wrapped code. Like this:
selection = window.getSelection().toString();
wrappedselection = '<span class="accent" style="somestyle">' + selection + '</span>';
document.execCommand('insertHTML', false, wrappedselection);
This will remove breaklines, tags like <b>
, <i>
and other intext-html-formatting - to keep them you need smth like this (thx to post):
selection = window.getSelection().getRangeAt(0).cloneContents();
span = document.createElement('span');
span.appendChild(selection);
wrappedselection = '<span class="accent1">'+span.innerHTML+'</span>';
document.execCommand('insertHTML', false, wrappedselection);
This insertHTML does not works with IE. Check Documentation https://developer.mozilla.org/en-US/docs/Web/API/Document/execCommand
I got the solution.
Javascript:
function line(){
window.execCommand('formatblock', false, 'p');
selectedElement = window.getSelection().focusNode.parentNode;
selectedElement.style.marginBottom = '100px';
}
HTML
<input type="button" value="addMarginBottom" onclick="javascript:line();"/>
<div class="textcontent" contenteditable ="true"></div>
This is work perfectly for me. But i can not make jsfiddle right now. This is work for one line fine but not multiple line.
Try this code: http://jsfiddle.net/lotusgodkk/GCu2D/57/
Javascript:
$(document).ready(function () {
$('div').click(function () {
var sel = window.getSelection();
var range = document.createRange();
el = document.getElementById('one'); //Get the element
range.selectNodeContents(el);
sel.removeAllRanges();
sel.addRange(range);
document.execCommand('formatblock', false, null); //execute command.
document.execCommand('bold', false, null); //execute command.
});
});
HTML
<div contenteditable="true">
<p id="one">Sample text</p>
<p>Sample text 2</p>
</div>
To add the class to the p tag, I think it should actually be like this...
function CssFnctn() {
document.execCommand('formatblock', false, 'p')
var listId = window.getSelection().anchorNode.parentNode;
listId.classList = 'oder2';
}
Notice the anchorNode instead of focusNode
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With