How to appendChild a generated div under a manually created div? - javascript

I have a div element that is generated by a javascript library. Let's assume the ID for it is auto
And I manually created a HTML div element with an ID of manual.
How do I move the generated div#auto into div#manual?
The div elements that are generated are not part of the document tree.
So I can't just appendChild to put auto under manual
Any idea?
var element = document.createElement("div");
element.id = 'generated';
var el = document.getElementById('element');
console.log(el)
<div id="manual">Place #generated as child of me</div>
As you can see, I can't target the generated div element #generated because it is not in the document tree. If I can't select it, I can't place it under #manual.

In your code:
var element = document.createElement("div");
element.id = 'generated';
var el = document.getElementById('element');
console.log(el)
element is already a reference to the element. There's no reason to try to look it up again via getElementById; just use the reference you have. getElementById won't find it, because it's not in the DOM yet.
So just use element:
var element = document.createElement("div");
element.id = 'generated';
document.querySelector("#manual").appendChild(element);
// -------------------------------------------^
At that point, it's in the DOM and getElementById would find it (though, again, you don't need to; you already have a reference to it in element).
Live Example: (I've added borders and given the generated div some content to make it clear what the result is)
var element = document.createElement("div");
element.id = 'generated';
element.innerHTML = "generated";
document.querySelector("#manual").appendChild(element);
div {
border: 1px solid black;
padding: 2px;
}
<div id="manual">Place #generated as child of me</div>
Note that there's no need for the id on the generated div for you to do this. If you have a different reason for it having an id, that's fine, but you don't need it for this:
var element = document.createElement("div");
element.innerHTML = "generated";
document.querySelector("#manual").appendChild(element);
div {
border: 1px solid black;
padding: 2px;
}
<div id="manual">Place generated div as child of me</div>

Related

H1 within DIV not responding to ActionListener which is set for DIV - pure JavaScript

So basicily what I am trying to do is to set ActionListener for whole div that I'm generating after some user action. Inside of that div I have an h1 marker and some text. When I click on the h1 the ActionListener is not responding. If I click anywhere else inside of div everything is working properly. I am setting ActionListener for parent div with id "list".
document.getElementById("list").addEventListener("click", function(event) {
if ( event.target.className === 'note') {
var id = event.target.id.slice(-1);
document.getElementById("title").value = titles[id];
document.getElementById("typedtext").value = notes[id];
}
});
this is how I generate the DIV:
const divNote = document.createElement("div");
const h1 = document.createElement("H1");
h1.setAttribute("id", "h" + number_of_notes);
const titleNode = document.createTextNode(title);
h1.appendChild(titleNode);
const textNode = document.createTextNode(text);
divNote.classList.add("note");
divNote.setAttribute("id", "n" + number_of_notes);
divNote.appendChild(h1);
divNote.appendChild(textNode);
document.getElementById("list").appendChild(divNote);
How to make the whole div to be sensitive to ActionListener?
You shouldn't update the html with innerHTML, but rather append a div to your parent with appendChild.
Here's what it would look like:
const myElement = document.createElement("div");
myElement.classList.add("note");
/* Other stuff to create the div... */
document.getElementById("list").appendChild(myElement)
The problem with modifying the innerHTML is that this will overwrite any previous DOM and all of your eventListeners will be detached.
cf: addEventListener gone after appending innerHTML

javascript create div and append it next to a child element without id

Using the solution suggested here: https://stackoverflow.com/a/32135318/10279127 i'm trying to create a new div, and append it inside a parent div with id, next to a child <a> html element.
html:
<div id="div0">
anchor text
// I'd like to place the new div here
</div>
js:
Element.prototype.appendAfter = function(element) {
element.parentNode.insertBefore(this, element.nextSibling);
}, false;
var NewElement = document.createElement('div');
NewElement.id = 'newDivID';
var tToAfter = $('#div' + index + ' > a'); // this is what i tried but doesn't work
NewElement.appendAfter(tToAfter);
If inside .appendAfter(...) instead of tToAfter i write document.getElementById('randomElementId') it works and appends it, so i think must be pure javascript, is there a way in js to do something like: document.getElementById('div' + index).firstChild to get the <a> ?
Or to make it entirely with jQuery using the insertAfter (https://stackoverflow.com/a/8707793/10279127) ?
you can select inside div#div0 by using
const anchor = document.querySelector("#div0>a");
You can simplify your approach by using insertAdjacentElement. For example (the css is irrelevant - just there so you can visually see the inserted div):
const anchor = document.querySelector('#div0 a');
const elem = document.createElement('div');
elem.id = 'newDivID';
anchor.insertAdjacentElement('afterend', elem);
div:not(#div0) {
height: 20px;
background-color: green;
}
<div id="div0">
anchor text
// I'd like to place the new div here
</div>

jQuery nest appends

is it possible to nest appends in jQuery??
I tried to do this:
var div = $('#ui-container');
var div2 = div.append( $('<div/>').addClass('second') );
var div3 = div2.append( $('<div/>').addClass('third') );
I want this:
<div id='ui-container'>
<div class='second'>
<div class='third'></div>
</div>
</div>
But I get this:
<div id='ui-container'>
<div class='second'></div>
<div class='third'></div>
</div>
You have to do it like below,
var div = $('#ui-container');
var div2 = $('<div/>').addClass('second').appendTo(div);
var div3 = div2.append($('<div/>').addClass('third'));
by using .appendTo(). Because .append() will return the object over which the append function was called. That is why you are seeing such result in your case.
#Rajaprabhu Aravindasamy has the correct answer. I thought I would go a little more in depth and add a jsfiddle.
Use appendTo() instead of append. Here's a quote from http://api.jquery.com/appendto/
The .append() and .appendTo() methods perform the same task. The major difference is in the syntax-specifically, in the placement of the content and target. With .append(), the selector expression preceding the method is the container into which the content is inserted. With .appendTo(), on the other hand, the content precedes the method, either as a selector expression or as markup created on the fly, and it is inserted into the target container.
Here's the markup:
var div = $('#ui-container');
var div2 = $('<div>div2<div/>').addClass('second').appendTo(div);
var div3 = $('<div>div3<div/>').addClass('third').appendTo(div2);
Try:
var div = $('#ui-container');
var div2 = $('<div/>').addClass('second');
div2.append( $('<div/>').addClass('third') );
div.append(div2);
jquery methods typically return the DOM node that they are being called on.
Therefore
var div2 = div.append( $('<div/>').addClass('second') ); // returns $('#ui-container')
It is also standard to reference DOM elements with a $ such as $div.
Here is a verbose solution
// Grab container
$div = $('#ui-container');
// Create first child
var div2 = '<div class="second"></div>'
// Append .second to #ui-container
$div.append(div2);
// Grab .second from the DOM
var $div2 = $('.second');
// Create grandchild element
var div3 = '<div class="third"></div>'
// Append to .second
$div2.append(div3)
codepen
All of your variables div, div2 and div3 refer to the same element $('#ui-container'). Easiest way to understand what you did would be to rename your variables, so you can see what happens:
/* What you did is this: */
var container = $('.result1');
var containerWithSecondAppended = container.append( $('<div/>').addClass('second') );
var containerWithThirdAppended = containerWithSecondAppended.append( $('<div/>').addClass('third') );
/* What you wanted to do is this: */
var div = $('.result2');
var div2 = $('<div/>').addClass('second');
var div3 = $('<div/>').addClass('third');
div.append( div2.append(div3) );
div {
padding: 10px;
border: 1px solid black;
}
.result {
margin: 10px;
padding: 10px;
}
.second {
background: none yellow;
}
.third {
background: none green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="result result1"></div>
<div class="result result2"></div>
Also on Fiddle.
jQuery append method will return a jQuery element, the one that was appended (changed).

Javascript - Get element behind caret in child elements of [contenteditable]

I am building a simplistic and easy-to-use text editor in Javascript, basically a WYSIWYG editor. I will be using the contenteditable attribute to the main wrapper (.wrapper). When you press enter inside the .wrapper, a new <p> element with a unique id gets appended to the wrapper.
I need a way to fetch which child element of the .wrapper that is currently selected (i.e., being focused or having the caret/text marker inside of it).
I've searched for days without any results, and I've tried using document.elementFromPoint() but without any proper results.
When using $(":focus"), I get the entire .wrapper and not the specific child element.
Edit:
Example HTML structure:
<div class="container t-wrapper" contenteditable>
</div>
Example Javascript code:
$(document).ready(function() {
$currentElement = $("[contenteditable]");
$(".t-wrapper").each(function() {
var id = generateIdentifier(6); // Ignore this
/* This creates the initial <p> child element, where you start typing. */
$(this).html('<p class="t-empty t-first" id="' + id + '"></p>');
$(this).on("mouseup", function() {
/* $currentElement = whatever element the caret is inside. */
});
$(this).on("keyup", function() {
/* $currentElement = whatever element the caret is inside. */
});
));
});
Edit 2:
I managed to get it fairly working with the mouseup event, since you're actually clicking on something. But I need this to work when moving the caret using the keyboard. Alternatively, I need some way to get the position of the caret in pixels, and then use document.elementFromPoint() to get the specific element.
:focus doesn't select your elements because they are not focusable.
You can make them focusable by adding tabindex="-1" in HTML, or tabIndex = -1 in JS.
var generateIdentifier = Math.random;
var currentElement = document.querySelector("[contenteditable]");
[].forEach.call(document.querySelectorAll(".t-wrapper"), function(el) {
var first = document.createElement('p');
first.className = "t-empty t-first";
first.id = generateIdentifier(6);
first.textContent = 'Press enter to create new paragraphs';
first.tabIndex = -1;
el.appendChild(first);
});
.container > :focus {
border: 1px solid blue;
}
<div class="container t-wrapper" contenteditable></div>
It seems that if you add it to the first paragraph, new paragraphs obtain it automatically. But if you want to be sure, I guess you could use a mutation observer or a keyup event listener to detect paragraphs without tabindex, and add it:
el.addEventListener("keyup", function(e) {
var newChild = el.querySelector('p:not([tabindex])');
if(newChild) newChild.tabIndex = -1;
});
document.activeElement will return the currently focused element.

JavaScript: how to change CSS style of created span?

newNode = document.createElement("span");
newNode.innerHTML = "text";
range.insertNode(newNode);
Is it possible to make the text in innerHTML with red background color? I want to add style="background-color:red" to just created span. Is it possible? Or it must have some id, and then I can change this span with jQuery?
Simple enough:-
newNode.style.backgroundColor = "red";
Better to give a classname for the span
<style>
.spanClass { background-color: red; }
</style>
newNode.className = "spanClass";
This worked for me:
var spanTag1 = document.createElement('span');
spanTag1.innerHTML = '<span style="color:red">text</span>';
OR
add class using js and set css to that class
var spanTag1 = document.createElement('span');
spanTag1.className = "mystyle";
Now set style to that class
<style>
.mystyle {
color:red;
}
</style>
You can add attributes directly to the DOM object. The style attribute can be assigned by this way too. Example:
var span = document.createElement("span");
span.setAttribute("style","color:white;background-color:red;");
var text = document.createTextNode("My text");
span.appendChild(text);
Of course you have to add this element created to their parent object in your page:
var parent = document.getElementById("parentObject");
parent.appendChild(span);
This method "setAttribute()" lets you to add other non-standard attributes used by animations and custom jquery options to your HTML standard tags.

Categories

Resources