Duplicate an element independently of the original - javascript

Im trying to duplicate a class and to make it not change when the original is changed. currently I tried
$(".newclass").addClass("oldclass");
which does not copy the content
var _elementClone = $(".oldclass").html();
$(".newclass").html(_elementClone);
this one is good and transfers all the contents of the div
PROBLEM: in all cases when I change the oldclass parent. like
$('.oldclass').hide();
<style>
.oldclass{visibility:collapse}
</style>
the new one also changes.
How can I create new class which does not change when the parent is changed?

You can duplicate the element by getting it's outer HTML, use jQuery to change it's id, class or whatever, and then insert it into the DOM to have independent elements.
EXAMPLE
HTML:
<div id="first" class="top">First Div</div>
<div id="second" class="middle">Second Div</div>
<div id="third" class="middle">Third Div</div>
<div id="last" class="bottom">Last Div</div>
Javascript:
var divs=$(".middle");
$.each(divs,function(i,el) {
var newdiv = $(el.outerHTML);
newdiv.attr("id",newdiv.attr("id")+"-copy");
newdiv.removeClass("middle").addClass("middle-copy");
divs.eq(i).after(newdiv);
});
$("#second-copy").html("copy of second div");
$("#third").html("original third div");
setInterval('$(".middle-copy").toggle()',1000);
Fiddle: http://jsfiddle.net/0cy0gvj9/2/

In the first line you're assigning .newclass to .oldclass. So, when later you hide .oldclass, this selector will include the previous assignment. That is, since all .newclass items are also .oldclass ones, they get hidden as well.
The function you're looking for is .append(), which will append a child to a given element (thus making it a parent).

Related

Should display:none element still have length = 1?

I'm just wondering if an element with display: none should have a length of 1 in JavaScript. I though display: none was like removing an element from the document and the known universe.
e.g.
$('.element').hide(); // jQuery sets to display: none;
console.log($('element').length); // returns 1
The display:none property is just use to hide the element, it will not remove the element form the DOM.
If you open the console and look into the Elements tab you will still see the element with display:none.
If you want to remove the element then you could use javascript to remove it from DOM.
Example
let elem = document.querySelector(`<css selector>`);
elem.remove();
All that display: none does is it changes the CSS style property of the element. The element still exists in the document, so it's still possible to select it with jQuery or a DOM method. Eg, both
<body>
<div>foo</div>
</body>
and
<body>
<div style="display: none">foo</div>
</body>
exist in the document.
If you want to actually remove the element from the DOM, use .remove() (in both jQuery and built-in JS):
$('.element').remove();
or
document.querySelector('.element').remove();
Both of those will result in the DOM changing from
<body>
<div class="element">foo</div>
</body>
to
<body>
</body>
One more thing is when you use the
$('.element').remove();
or
document.querySelector('.element').remove();
be aware that: The remove() method removes the selected elements, including all text and child nodes.

Delete only the particular Div Id

<div id="#("Bottomgrid)" class="dgd2"></div>
var element = document.getElementById("#Bottomgrid");
element.empty();
$('.dgd2').empty()
Instead of deleting only Bottom grid its also removing other Div present in the screen.
jQuery .remove() will remove the set of matched elements from the DOM.
While jQuery .empty() will remove all child nodes of the set of matched elements from the DOM.
Considering if you have your HTML as below :
<div id="Bottomgrid" class="dgd2"></div>
and you want to remove div with id="Bottomgrid"
Then your javascript code will be :
$("#Bottomgrid").remove();
//This is not required as far as I see
//$('.dgd2').empty()
If you have a HTML structure like this:
<div class="holder">
<div id="item1">Hey</div>
</div>
you can simply just use this pure JavaScript code to remove the "item1" element:
var element = document.getElementById("item1");
element.parentNode.removeChild(element);
.empty() doesn't remove element it only removes elements children. use $('#Bottomgrid').remove()
Javascript :
document.getElementById("Bottomgrid").remove();
Jquery:
$( "#Bottomgrid" ).remove();
you should give the div name properly like Below how I am writing the Id. also you need to check properly which div you are going to delete. Because if a nested div present in your page and you are going to delete the div which is having all the child div inside that , then all respective div going to be deleted .
Html
<div id="bottomgridDiv" class="dgd2">
<div id="parentDiv" class="dgd2">
<div id="childDiv" class="dgd2">
</div>
</div>
</div>
Javascript
var element = document.getElementById("#bottomgridDiv");
In JQuery:-
$("#bottomgridDiv").remove();
So now if you wants to delete the bottomgridDiv then what ever the div present inside this is going to delete.

Append element to a div only inside the parentcontainer

How do I append .div4 to .div1 onLy on its parent container without it also appends to the next container with the same div? I tried the basic jQuery appendTo but this sets .div4 on all the .div1 elements in my DOM.
<div class="container">
<div class="div1"></div>
<div class="div2"></div>
<div class="div3"></div>
<div class="div4"></div>
</div>
<div class="container">
<div class="div1"></div>
<div class="div2"></div>
<div class="div3"></div>
</div>
Update: changed invalid HTML. Using this script now (replace dummy divs with my actual divs):
var $this = $('span.conditionHilite.refurbHilite');
$this.appendTo($this.closest('.itembox.centerbox.col.span_1_of_3').find('.image.col1'));
Problem now is that if my page consist of more then one container with"span.conditionHilite.refurbHilite" it will append the total amount of these elements inside each parentcontainer instead of just the one.
If you tried to append an element to more than one target element with jQuery, it will clone that element however many times is required. If you only want to append .div4 to the .div1 element within its same container element, you'll need to explicitly select that element. Something like this:
var $this = $('.div4');
$this.appendTo($this.closest('.container').find('.div1'));
That uses .closest() to traverse up the DOM tree to find the containing element, then .find() to look within that containing element for the .div1 element. With your current DOM structure that will only ever be a single element, so the .div4 element is simply moved, without any clones being created.
Note: As Rory McCrossan pointed out, you're re-using IDs in your HTML and it is therefore invalid. I've used a class selector in the code above on the assumption that you'll fix your invalid HTML by switching from id="container" to class="container". If - as stated in the comments - you absolutely can't change that, then the '[id="container"]' selector should work instead.

Appending a div on unknodw div

I have three divs. How should I append a div onto an unknown div?
<div class="main" >
<div id="drag-box" >
<div id="" class=""> </div>
</div>
</div>
I want to append div on an unknown div which is come after drag-box div. I don't know which div comes after drag-box div. But there must be one div after drag-box div.
$("#drag-box div:first-child").append("<span />");
or
$("#drag-box div").first().prepend("<span>first</span>");
For a complete answers, here it is working:
http://jsfiddle.net/dMUD3/
try this
$("#drag-box div:first-child").attr("id");
Instead of giving you a one liner I would like to give you an indepth solution.
A browser takes your html and parses what is called a DOM Tree out of it.
so if your html is .
<div class="a">
<div class="foo"></div>
<button class="foogle"></button>
</div>
The tree structure will become something like
`-div.a
|-div.foo
`Button.foogle
You should actually look into DOM Api's at MDN
How DOM helps ?
With DOM api's you can actually access the unknown div using the reference to a known div. So if you actually understand your markup and its representation in DOM it should be pretty simple to get reference to nth child of an element;
You can access the child elements by the children attribute.
So
// Get reference to the element.
var parent = document.getElementById("drag-box");
// Use the dom.
var child_i_want = parent.children[0];
// or there is another way
var child_i_reallyWant = parent.firstElementChild;
There are solutions with jQuery but I feel its important for you to Understand basics of DOM even when there are helpful abstraction libraries in existance.
You'll need the + selector. It applies to the object directly following. See here.
.drag-box + div {
}
$('<div></div>').appendTo($('#drag-box div:first'))

Why is this small javascript not working?

I have multiple instances of a div with an id of "myDiv" on a page. I want to replace the contents of these divs. When I use this javascript:
function replaceContent(id, content) {
var container = document.getElementById(id);
container.innerHTML = content;
}
replaceContent('myDiv', 'hello there');
<div id="myDiv"></div>
<div id="myDiv"></div>
<div id="myDiv"></div>
It only replaces the content inside one of those divs and not all of them. If I use the .html() function of jquery instead, it replaces the contents of all divs. Is there any way I can get the above js to work in the same way?
id values must be unique - you can't have more than one id with the same name and update all of them.
I have multiple instances of a div with an id of "myDiv" on a page.
This is where you're doing it wrong. You cannot assign an ID to multiple elements on a page - it has to be unique.
It only replaces the content inside one of those divs and not all of them.
This happens because getElementById() returns only the first-matched element in case multiple such elements are matched.
To solve this, assign a class instead of an ID to the divs you want to target, and if you can use jQuery, use this instead (assuming class="myDiv"):
function replaceContent(className, content) {
$('div.' + className).html(content);
}
// This appends className so the selector becomes $('div.myDiv')
replaceContent('myDiv', 'hello there');
IDs have to be unique. You can use the same class name for all divs and then use a css selector.
<div id="div1" class="mydivs">blah</div>
<div id="div2" class="mydivs">blah123</div>
For e.g. In JQuery, you could do:
$('.mydivs').html("whatever");

Categories