Javascript check if exists and if not exists
Javascript check if exists and if not exists
by Adi Jaya
HTML
<div id="bar">
<button onclick="cmd('bold');">B</button>
<button onclick="cmd('italic');">I</button>
<button onclick="cmd('underline');">U</button>
<button onclick="viewsource();">Source</button>
</div>
<iframe id="editor"></iframe>
<textarea style="display:none;" id="textarea"></textarea>
CSS
*{
box-sizing: border-box;
}
iframe,textarea {
display : block;
width : 100%;
min-height:100px;
border : 1px solid silver;
margin : 10px 0;
resize : vertical;
}
JavaScript
/*
if (selector) {
//Do something if exists
}
if (!selector) {
//Do something if not exists
}
*/
/*example*/
var target = document.getElementById('editor');
if (target) {
var editor = target.contentDocument||target.contentWindow.document;
editor.designMode = 'on';
editor.execCommand('defaultParagraphSeparator', false, 'p');
var source = target.contentDocument.getElementsByTagName('body')[0];
function cmd(key){
editor.execCommand(key);
}
function viewsource(){
var a = document.getElementById('textarea');
a.style.display= "block";
a.value= source.innerHTML;
}
//and more....
}
if (!target) {
alert("Element [id=editor] not found");
document.getElementById('bar').innerHTML="";
}