Dynamic div containing selected text inside another div - javascript

I have a div element. I will copy-paste some text in this div. Then, upon clicking a create button, another div will be created inside the div with the selected text inside it. The new div will have a different background-color, different fonts, and other style properties. But my code isn't working. Please help me to figure out the mistakes. Thanks!!
<html>
<head>
<title>select</title>
<style>
</style>
</head>
<body>
<script>
function changeit(){
var slctn = document.getSelection();
var strings = slctn.toString();
alert(strings);
var get_id = document.getElementById("myspace");
var elem = document.createChild("div");
var design = document.createAttribute("style");
design.value = "background-color:white;color:red;font-weight:bold;font-style:italic;font-family:CURSIVE;";
elem.setAttributeNode(design);
elem.createTextNode(now);
get_id.appendChild(elem);
alert("it is done");
}
</script>
<div contenteditable="true" width="400px" height="500px" style="background-color:pink;display:block;" id="myspace">ddd</div>
<input type="button" value="select" onClick="changeit();">
</body>
</html>

For create div element you should use
var elem = document.createElement("div");
instead of
var elem = document.createChild("div");
And createTextNode is performed over document something like
document.createTextNode('now');
Working DEMO

<script>
function changeit(){
var slctn=document.getSelection();
var strings=slctn.toString();
alert(strings);
document.getElementById("myspace").appendChild('<div style="background-color:white;color:red;font-weight:bold;font-style:italic;font-family:CURSIVE;">'+document.getElementById("myspace").innerHTML+'</div>');
}
</script>
Works?

Related

Adding selected number of divs inside another div

Im trying to create an app that will roll number of dice decided by the user.
I want every dice to be in a separate div but I struggle to implement a code inserting divs into HTML.
As a test I created a button that would insert a single div into another div, here is what I got so far:
<div id="diceTable">
<button onclick="addDice()">Add Dice</button>
</div>
JS being:
function addDice(){
var div = document.createElement('div');
div.innerHTML = "<p> here will be a dice</p>";
div.getElementById('dice').appendChild(div);
}
But it doesnt seem to work. Maybe im using wrong methods.
Small typo - use document.getElementById('dice').appendChild(div) instead of div.getElementById('dice').appendChild(div).
function addDice() {
var div = document.createElement('div');
div.innerHTML = "<p> here will be a dice</p>";
document.getElementById('dice').appendChild(div);
}
<div id="diceTable">
<button onclick="addDice()">Add Dice</button>
</div>
<div id='dice'></div>
This is straight out of W3C school https://www.w3schools.com/jsref/dom_obj_div.asp
<script>
function myFunction() {
var x = document.createElement("DIV");
var t = document.createTextNode("This is a div element.");
x.setAttribute("style", "background-color: pink;");
x.appendChild(t);
document.body.appendChild(x);
}
</script>
Use append.child rather than innerHTML

div - createElement is not working?

I'm trying to create the div tag using javascript.? But why it is not working?
I have seen the document.createElement not working
Javascript createElement() not working in Chrome
But these answers are not suited for my script.
<html>
<head>
<script>
var div = '<div id = con style="width:auto; height:200px; Background:#2a2a2a">';
var x = document.createElement(div);
var y = document.getElementById('con');
y.innerHTML = "hello world";
document.body.appendChild(x);
</script>
</head>
<body>
</body>
</html>
How can I do it?
It doesn't work like so. .createElement() only excepts the type of element you want to create, no predefined HTML snippet. So you have to create a Div Element using document.createElement('div'); and work on that element afterwards. Like
For Instance
var div = document.createElement('div');
div.id = 'con';
div.style.cssText = "width:auto; height:200px; Background:#2a2a2a";
document.body.appendChild( div );
If you don't need a reference to an Element and you only want to insert new HTML code, you can also use Element.prototype.insertAdjacentHTML() like so
document.body.insertAdjacentHTML( 'beforeend', '<div id="con" style="width:auto; height:200px; Background:#2a2a2a">');
A further problem of your code here is that you try to access the DOM too early. Even if the code would work in its current form, you cannot access document.body in your <head> section because it wasn't fully initialized at that point. Either move the entire <script> source into the <body> section or attach a listener to DOMContentLoaded Event.
If you want to insert entire HTML structure all at once, you can use very useful, cross-browser and unfairly little known insertAdjacentHTML method:
var div = '<div id="con" style="width:auto; height:200px; Background:#2a2a2a"></div>';
document.body.insertAdjacentHTML('beforeend', div);
var y = document.getElementById('con');
y.innerHTML = "hello world";
You cannot create a predefined html like that, also since you are appending to body, the script should be inside the body element not in head
<html>
<head>
</head>
<body>
<script>
var x = document.createElement('div');
x.id = 'con';
x.style.width = 'auto';
x.style.height = '200px';
x.style.background = '#2a2a2a';
x.innerHTML = "hello world";
document.body.appendChild(x);
//no need to access `y` by id, use the reference returned by createElement to set the content
//var y = document.getElementById('con');
//y.innerHTML = "hello world";
</script>
</body>
</html>

removeChild with addEventListener

I'm just learning javascript. Testing stuff on the google Chrome Console I ended up with this:
<html>
<head></head>
<body>
<div id="divi">
<button id="butti">Click Me</button>
</div>
</body>
</html>
And Js:
function cBoton (){
var getDiv = document.getElementById("divi");
getDiv.removeChild(getDiv.lastChild);
};
var getButton = document.getElementById("butti");
getButton.addEventListener("click", cBoton);
I expect the button to be deleted after one click. ¿Why works only after the second click?
tx!
The .lastChild of the element in your markup is "" (try console.log(getDiv.lastChild) to clarify).
Use this to be sure that you are deleting the desired element:
function cBoton() {
var getDiv = document.getElementById("divi");
getDiv.removeChild(getButton);
};
On the first click, the last child of divi is the text node containing the whitespace after the button, and this gets removed. On the second click, the button is the last child.
Invaluable..
Modified the source;
/* .css */
div :nth-child(even){background-color: #f2f2f2}
/*.js */
function addDiv() {
var para = document.createElement("p");
var node = document.createTextNode('textHere'); // add cell code here
para.appendChild(node);
var element;
element = document.getElementById("div1"); // to add div id recursion
element.appendChild(para);
}
function cBoton (){
var getDiv = document.getElementById("div1");
getDiv.removeChild(getDiv.lastChild);
}
var getButton = document.getElementById("div1");
getButton.addEventListener("click", cBoton);
/* HTML */
<html>
<head></head>
<body>
<button onclick="addDiv()">add</button>
<button onclick="cBoton()">Click Me</button>
<frameset><legend>recursions</legend>
<div id="div1"></div>
</frameset>
</body>
</html>

issues inserting a div from Javascript

I'm trying to add a div with some text before another div in the document.
Here's my script in a nutshell, assume init() gets called when onload page:
<head>
<script type="text/javascript">
function init () {
var div = document.createElement('div').className = 'title';
div.innerHTML = 'Hello';
var reference = document.getElementById('content');
document.body.insertBefore(div, reference );
}
</script>
</head>
<body>
<div id="content">blah blah</div>
<br /><br />
</body>
I get a type mismatch error on document.body.insertBefore(div, reference), Can someone please let me know what i'm doing wrong?
Try
function init () {
var div = document.createElement('div');
div.className = 'title';
div.innerHTML = 'Hello';
var reference = document.getElementById('content');
document.body.insertBefore(div, reference );
}
You were setting the div to the string title I think (never checked)
Yep here you go
http://jsfiddle.net/FxFzc/

Chrome: How to insert two consecutive spans into editable body without nesting them

I am trying to insert two consecutive spans into an editable body element on Chrome. My problem is that the 2nd span is ending up inside the first span instead of next to it.
I have simplified my example, but in real life, the end user might have moved the cursor or selected some text in between the two inserts.
<html>
<head>
<script>
function load(){
insert("<span style='color:red'>hello</span>");
insert("<span>goodbye</span>");
}
function insert(sHtml){
var oSel = window.getSelection();
var oRange = oSel.rangeCount > 0 ? oSel.getRangeAt(0) : void 0;
if(!oRange){
oRange = window.document.createRange();
oRange.selectNodeContents(window.document.body);
}
var newFrag = oRange.createContextualFragment(sHtml);
oRange.insertNode(newFrag);
oRange.collapse(false);
oSel.removeAllRanges()
oSel.addRange(oRange);
}
</script>
</head>
<body onload="load()">
</body>
</html>
You're doing strange and complex things to insert your nodes. Why using the selection ?
Using jquery, you could define your insert function like this :
function insert(html) {
$("body").append(html);
}
Without jquery, you would have to add the node and set a text in the node :
var newNode = document.createElement("span");
newNode.setAttribute("style", "color:red");
newNode.appendChild(document.createTextNode("hello"));
document.body.append(newNode);

Categories