jQuery nest appends - javascript

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).

Related

Create a custom element in place where the code was initialized

I'm trying to create an element using JavaScript in place where the script was initialized.
I need to be able to just call a function for the element to appear just after the <script> tag in my HTML document.
I tried this code but I don't know how to actually create an element.
function createElement() {
var container = document.createElement('div');
container.setAttribute("class", 'someDiv');
document.createElement(container);
}
.someDiv {
height: 100px;
width: 100px;
background-color: gold;
}
<body>
<script>
createElement("div", "someDiv");
</script>
</body>
document.currentScript seems to have good browser support, and will give us the script element containing the code currently being executed.
If what you'd like to do is replace the current script with some other element, you use it like this:
<script>
const replacementText = document.createTextNode("hi, I'm the replacement!");
document.currentScript.parentNode.replaceChild(replacementText, document.currentScript);
</script>
If you simply want to insert an element after the current script, without replacing it:
<script>
const newText = document.createTextNode("hi, I'm new text!");
const currentScript = document.currentScript;
currentScript.parentNode.insertBefore(newText, currentScript.nextSibling);
</script>
Here's a more complex example using prewritten HTML:
<script>
const currentScript = document.currentScript;
const templateFragment = (function(){
const templateEl = document.createElement("template");
templateEl.innerHTML = `
<ul>
<li>Hi!</li>
<li>I am a list!</li>
</ul>
`;
return templateEl.content;
})();
currentScript.parentNode.insertBefore(templateFragment, currentScript.nextSibling);
</script>
You could use insertBefore and target insertion point as the script like so:
var script = document.querySelector('script:last-of-type');
var container = document.createElement('div');
document.body.insertBefore.insertBefore(script, container);
Using document.currentScript, we can get a reference to the script element where the code is running and then using .nextElementSibling, we can get the next sibling node that is an element. Finally, with .insertBefore and .appendChild(), we can insert the new element just before the element passed in as an argument (the sibling that was found earlier or body if none was found).
NOTE: Don't call your function createElement as it can cause a naming conflict with document.createElement().
This will insert an element just after the script element.
.someDiv {
height: 100px;
width: 100px;
background-color: gold;
}
<head>
<script>
function create(type, style) {
var container = document.createElement(type);
container.classList.add(style); // Best way to add a class
container.textContent = "Hello!";
let sibling = document.currentScript.nextElementSibling;
if(sibling){
// Insert the new element before the next sibling
sibling.parentNode.insertBefore(sibling, container)
} else {
// Insert the new element at the end of the body
document.body.appendChild(container);
}
}
</script>
</head>
<body>
<p>The new element should be right below this.</p>
<script>
create("div", "someDiv");
</script>
<p>The new element should be right above this.</p>
</body>
You can use .insertBefore() to add some element before the next sibling of your script. To reference your script, you could add an id attribute to it:
.someDiv {
height: 100px;
width: 100px;
background-color: gold;
}
<body>
<p>I'm inside the body, before the script TAG</p>
<p>New element should appear just after this text...</p>
<script id="myScript">
function createElement()
{
var container = document.createElement('div');
container.setAttribute("class", 'someDiv');
var script = document.getElementById("myScript");
script.parentNode.insertBefore(container, script.nextSibling);
}
createElement();
</script>
<p>I'm inside the body, but after the script TAG</p>
</body>

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>

Change Properties of Items using a forEach Method (javascript)

I'm using a javascript forEach method to iterate over items in an array, but it's throwing an error when I try and do something with the items.
In the code below when I console log 'item' it gives the desired behavior of logging 'div1, div2, div3' to the console. However, when I try and make a change to these items it won't allow it. The examples of using a forEach method in JS when you Google it is very abstract.
How do I use this method to change the background colors or other properties of the items?
Codepen link is here https://codepen.io/emilychews/pen/boJBKB
JS
var div1 = document.getElementById('div1');
var div2 = document.getElementById('div2');
var div3 = document.getElementById('div3');
var myArray = ['div1','div2','div3']
myArray.forEach(function(item){
console.log(item);
item.style.backgroundColor = "blue";
})
CSS
.div {height: 50px; width: 50px; background-color: red; margin-bottom: 10px;}
HTML
<div class="div" id="div1"></div>
<div class="div" id="div2"></div>
<div class="div" id="div3"></div>
Any help would be awesome
Emily
Remove the quotes like: var myArray = [div1,div2,div3]
your myArray contains Strings, not Dom Nodes.
try this code:
var div1 = document.getElementById('div1');
var div2 = document.getElementById('div2');
var div3 = document.getElementById('div3');
var myArray = [div1,div2,div3]
myArray.forEach(function(item){
console.log(item);
item.style.backgroundColor = "blue";
})

Trying to append child to all elements with same class name

I am trying to use the appendChild() method to add a document.createElement("div") element to multiple <div> elements with the same class name.
I have tried this way:
const childElement = document.createElement("div");
childElement.className = "second";
const parentObject = document.getElementsByClassName("first");
[...parentObject].map(parent => parent.appendChild(childElement))
Which didnt work, so I tried:
for(let i = 0; i < parentObject.length; i++){
parentObject[i].appendChild(childElement);
}
The only way it worked was if I wrote the html element myself and then added it to the innerHTML of each parent:
[...parentObject].map(parent => parent.innerHTML = "<div class='second'></div>")
But since I am generating all different kind of HTML element tags, like IMG, DIV, SPAN I need the convenience of calling the createElement() method.
Has anyone any experience with this?
An element can only exist in one place in the DOM. What you need to do is create a new element to append to each parent:
const parentObject = document.getElementsByClassName('first');
[...parentObject].forEach((parent, i) => {
const childElement = document.createElement('div');
childElement.className = 'second';
childElement.innerHTML = `second ${i}`;
parent.appendChild(childElement)
});
div { padding: 5px; }
.first { background-color: pink; display: inline-block; }
.second { background-color: lightblue; }
<div class="first">first</div>
<div class="first">first</div>
<div class="first">first</div>
<div class="first">first</div>

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

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>

Categories

Resources