Javascript appendChild if div not exists - javascript

i've working in a big project, and that i want is
if div 1 not contain div 2 child{
div1.appendChild(div2)
}
But, i'm getting problem to solve this
My code
<script>
dc = document.createElement("div");
dc.className = "doctor_card doctor-"+o+" hidden";
dcc.appendChild(dc);
</script>
Thanks for advice :)

Try this:
<script>
var className = "doctor_card doctor-"+o+" hidden";
if (dcc.getElementsByClassName(className).length == 0) {
dc = document.createElement("div");
dc.className = className;
dcc.appendChild(dc);
}
</script>

var dcc = document.getElementsByClassName('parentclass')[0];
if (!dcc.contains(dc)) {
dcc.appendChild(dc);
}
You can use above code if u really want to use pure javascript.

Related

jQuery to plain javascript

I need to change this bit of jQuery..
$(function() {
$("#breadcrump").append("<div id='oldsite'>Can't find what you're looking for? Try our old website: <a href='http://www.brooksbarn.co.uk'>Old Website (brooksbarn.co.uk)</a> or<a href='mailto:info#brooksbarn.co.uk?Subject=Brooksbarn.com Part Enquiry' target='_top'>E-Mail</a></div>");
});
Into regular javascript, I've looked into many ways, but my lack of js knowledge seems to be my stumbling block.
Here is what I've come up with so far:
document.body.onload = addElement;
function addElement () {
// create a new div element
// and give it some content
var newDiv = document.createElement("oldsite");
var newContent = document.createTextNode("Can't find what you're looking for? Try our old website: <a href='http://www.brooksbarn.co.uk'>Old Website (brooksbarn.co.uk)</a> or<a href='mailto:info#brooksbarn.co.uk?Subject=Brooksbarn.com Part Enquiry' target='_top'>E-Mail</a>");
newDiv.appendChild(newContent); //add the text node to the newly created div.
// add the newly created element and its content into the DOM
var currentDiv = document.getElementById("breadcrump");
document.body.insertBefore(newDiv, currentDiv);
}
Why do you don't do that :
document.getElementById("breadcrump").innerHTML += "<div id='oldsite'>Can't find what you're looking for? Try our old website: <a href='http://www.brooksbarn.co.uk'>Old Website (brooksbarn.co.uk)</a> or<a href='mailto:info#brooksbarn.co.uk?Subject=Brooksbarn.com Part Enquiry' target='_top'>E-Mail</a></div>";
?
There are a couple of things you can do, easiest would be to just set the string as innerHTML
(function(){
function addElem () {
var newDiv = document.createElement("div"); //create div
newDiv.id = "oldsite"; //sets id
newDiv.innerHTML = "Can't find what you're looking for? Try our old website: <a href='http://www.brooksbarn.co.uk'>Old Website (brooksbarn.co.uk)</a> or<a href='mailto:info#brooksbarn.co.uk?Subject=Brooksbarn.com Part Enquiry' target='_top'>E-Mail</a>"; //add html to new element
document.getElementById("breadcrump").appendChild(newDiv); //add it to the page
}
if (el.addEventListener) {
window.addEventListener('load', addElem , false);
} else if (el.attachEvent) {
el.attachEvent('onload', addElem );
}
}());
I think you should add these:
1 You are creating a div, not a oldsite tag
var newDiv = document.createElement("div");
2 You need to set the id
newDiv.id = "oldsite";
3 You are originally appending it:
document.body.insertBefore(newDiv, currentDiv.nextSibling);
http://jsfiddle.net/gf6gna1g/

javascript to hide a div if empty

I am looking for javascript (not jquery as client has specified) to hide a div with class=top, if the div has no content. I can do it using jquery like below, but need to use javascript. Any ideas please?
$('div.top:empty').hide();
Something like:
var top = document.getElementsByClassName("top");
for (var i = 0; i < top.length; i++) {
if (top[i].innerHTML.length == 0)
top[i].style.display = "none";
}
you could use innerHTML property to check if the selected div.top element contains content. something like this.
var topDiv = document.getElementsByClassName('top')[0];
if(topDiv.innerHTML === '') {
topDiv.style.display = 'none';
}
(if(document.getElementById("yourDiv").innerHTML=="")
{
document.getElementById("yourDiv").style.display='none';
}
You need to give id to DIV which you want to hide As there are no function in javascript by which you can find div by class.
HTML:
<div class="top" id="divId"></div>
Javascript:
if( document.getElementById("divId").innerHTML == "" )
{
document.getElementById("divId").style.display='none';
}
Use the following script:
var divContent = $('div .top')[0].innerHTML;
if (divContent === '')
{
$('div .top').hide();
}

Javascript not updating text within a div

I must be daft, but the javascript is not changing the containing div text as I would expect once the div is clicked:
favourite.onclick = function() {
loadXMLDoc('indexFavourite');
var linkclass = favourite.className;
if(linkclass == 'favouriteOption')
favourite.className = 'favouriteOptionActive',
favourite.className.update("New text");
else
favourite.className = 'favouriteOption';
}
Your syntax is way off, missing bracket and whatnot
favourite.onclick = function() {
loadXMLDoc('indexFavourite');
var linkclass = favourite.className;
if(linkclass == 'favouriteOption') {
favourite.className = 'favouriteOptionActive',
favourite.innerHTML="New text";
}
else {
favourite.className = 'favouriteOption';
}
}
What you are doing here is changing the class of a div (probably). And even this is kinda wrong. I mean
favourite.className = 'favouriteOptionActive',
favourite.className.update("New text");
should actually produce an error, because the string favouriteOptionActive doesn't have a method update. It could have only if you patch the String.prototype.
If you want to change the div's text you should use div.innerHTML or div.innerText.
favorite.text('New text') will set the text
note this will work if using jQuery, my bad!

get dynamic text in text area on every click on div

I want to open the CKEDITOR on click-event of div, and want the div contents in that textarea of ckeditor
but somehow this is not working.
Thanks in advance, and sorry for my poor english
function createEditor() {
$('DIV').click(function(event) {
var id1 = event.target.id;
//alert(id1);
document.getElementById("editor1").value = '';
var newtext = document.getElementById(id1).innerHTML;
alert(newtext);
document.getElementById("editor1").value += newtext;
});
document.getElementById("contents").style.display = "block";
}
Remove createEditor() function and try it
$('DIV').click(function(event) {
var id1 = event.target.id;
//alert(id1);
document.getElementById("editor1").value = '';
var newtext = document.getElementById(id1).innerHTML;
alert(newtext);
document.getElementById("editor1").value += newtext;
});
document.getElementById("contents").style.display = "block";
Try this to add data to the textarea.
$("#editor1").val(newtext);
or use
$('#editor1').append(newtext);
This solution will rely more on jQuery. First, if you want this function to be triggered when ever a div is clicked, get rid of your function(), it's not necessary since your event will be triggered every time a div is clicked.
This should solve your problems:
$('div').click(function(e) {
$id1 = $(this).attr("id");
alert($id1);
$("#editor1").val(' '); //Are you sure you want to empty your textarea?
$newtext = $("#"+$id1).html();
alert($newtext);
$("#editor1").val($newtext); //Because when you append the newtext it won't append but replace the text it's already on this.
$("#contents").css("display","block");
});
Here's a fiddle with a similar example of using your function:
If you just want the text of the clicked div and you're using jQuery try
$("div").click( function() {
var newtext = $(this).text();
$("#editor1").text( newtext );
});

Dynamicaly creating and removing a div

I have been strugling with this for a while and I am sure there is a simple answer to this. What happens is I remove a div called "payment" then dynamicaly create it again so I can add to it. That then gets repeated as the infomation that needs to be added to it changes.
I have mangaged to get this so far.
function clearPage()
{
var d = document.getElementById("contain");
var d_nested = document.getElementById("payment");
var deleteNode = d.removeChild(d_nested);
}
function createPayment()
{
payment = document.createElement("div");
payment.id = "mine";
document.getElementById("contain").appendChild(payment);
}
function printOnPage()
{
var x = names.length;
for( var i = 0 ; i < x ; i++ )
{
var para = document.createElement("p");
var paymentDiv = document.getElementById("payment");
paymentDiv.appendChild(para);
var txtName = document.createTextNode("Item: ");
para.appendChild(txtName);
var txtNameArray = document.createTextNode(names[i]);
para.appendChild(txtNameArray);
var txtQty = document.createTextNode(" Qty: ");
para.appendChild(txtQty);
var txtQtyArray = document.createTextNode(qty[i]);
para.appendChild(txtQtyArray);
var txtCost = document.createTextNode(" Cost: ");
para.appendChild(txtCost);
var txtCostArray = document.createTextNode(prices[i]);
para.appendChild(txtCostArray);
}
}
Related HTML
<div id="contain">
<p>Payment</p>
<div id="payment">
<br />
</div>
</div>
It needs the ID of payment for both my CSS rules and for my creating the text that goes in it.
This is the error I get in FireFox
Error: paymentDiv is null Source File:
http://itsuite.it.brighton.ac.uk/ks339/sem2/javascript/js.js Line: 76
Hope someone can provide some insight in to this and please tell me if I am completly off!
Thanks
Edit: Is it easior to clear the div rather than delete it, how would I go about doing such a thing?
In create_payment(), you set the ID to 'mine'. Shouldn't it be 'payment'?
I do not understand your requirements very well, but anyway you cannot create multiple items in the page using the same id attribute, if you want to duplicate an item and still have control over it, you should be using class instead.
Try switching your code into jquery it will be cleaner and easier to understand for you & me.
Your problem is the fact that in createPayment() you're setting the id to 'mine':
payment.id = "mine";
while later on in printOnPage() you're looking for the element using id 'payment':
var paymentDiv = document.getElementById("payment");
As you mention in your edit, it is far easier just to clear the div than to remove it, specially if you still need it later.
To clear a DIV-block just set it's content to empty:
document.getElementById('payment').innerHTML = "";
I hope you find a solution! Good luck!

Categories