I want to dynamically create a div element with id="xyz". Now before creating this, I want to remove any other div with id ="xyz" if it exists. How can i do it?
var msgContainer = document.createElement('div');
msgContainer.setAttribute('id', 'xyz'); //set id
msgContainer.setAttribute('class', 'content done'); // i want to add a class to it. it this correct?
var msg2 = document.createTextNode(msg);
msgContainer.appendChild(msg2);
document.body.appendChild(msgContainer);
}
How can i remove all divs with id =xyz if they exist before executing above code?
Removing:
var div = document.getElementById('xyz');
if (div) {
div.parentNode.removeChild(div);
}
Or if you don't control the document and think it may be malformed:
var div = document.getElementById('xyz');
while (div) {
div.parentNode.removeChild(div);
div = document.getElementById('xyz');
}
(Alternatives below.)
But you only need the loop with invalid HTML documents; if you control the document, there's no need, simply ensure the document is valid. id values must be unique. And yet, one sees plenty of documents where they aren't.
Adding:
var msgContainer = document.createElement('div');
msgContainer.id = 'xyz'; // No setAttribute required
msgContainer.className = 'someClass' // No setAttribute required, note it's "className" to avoid conflict with JavaScript reserved word
msgContainer.appendChild(document.createTextNode(msg));
document.body.appendChild(msgContainer);
If you don't like the code duplication in my loop above and you think you need the loop, you could do:
var div;
while (!!(div = document.getElementById('xyz'))) {
div.parentNode.removeChild(div);
}
or
var div;
while (div = document.getElementById('xyz')) {
div.parentNode.removeChild(div);
}
...although that last may well generate lint warnings from various tools, since it looks like you have = where you mean == or === (but in this case, we really do mean =).
Related
if(typeof this.description === 'undefined') {alert('No Description Set!'); return false;}
var tempDiv = document.createElement('div'); //create a div outside of the DOM
tempDiv.className = 'descriptionColumn formBox contentRow'; //make sure and use the
//same/equivlent class(s) to ensure accuracy
tempDiv.innerHTML = this.description; //insert the text
document.body.appendChild(tempDiv); //render div
lineHeight = parseInt($(tempDiv).css('line-height')); //get the line-height (make sure this is specified in CSS!)
//also we use Jquery here to handle any vender inconsistencies,
divHeight = tempDiv.clientHeight; //get the div height
tempDiv.parentNode.removeChild(tempDiv); //clean up, delete div
delete tempDiv;
return divHeight/lineHeight; //divide the height by the line-height and return
This code works, I am trying to calculate the number of lines in a div. That said I wasn't able to get the line-height until after I added this element to the DOM.
Origionally I planned on not adding it at all because I only use it to calcuate the number of lines in the DIV.
It makes sense that it wouldn't have a height until I added it, I am just wondering if I did the right thing, or if there is a way to get the line-height without adding it to the DOM in the first place.
Rendering/Layout decision by browser is taken by browser 2 conditions:
1)new element is inserted
2)some element's style has been changed
3)sometimes when window is resized
so until the element is in DOM Tree browser will not give Layout related style to it.
consider following code:
var div = document.createElement(div);
var style = window.getComputedStyle(div);
console.log( style.color );//prints "" (empty string)
why??
because window.getComputedStyle() returns the CSS style which are actully present in DOM(browser).
now,
document.body.appendChild(div);
var style = window.getComputedStyle(div);
console.log( style.color );//prints rgb(somevalue)
why??
because rendering engine has decided the CSS properties.
//One gotcha
var div2 = document.createElement("div");
div2.style.color = "red";
console.log( $(div2).css("color") ); //prints red because jQuery gives preference to div2.style.color over window.getComputedStyle(div2);
but console.log ( window.getComputedStyle(div2).color );//prints "" .... this proves that browser has not yet decided the properties of div2
Yes, it is. But ... if you have jQuery on your page, why don't you use it?
var $div = $('<div/>', {
class: 'descriptionColumn formBox contentRow',
text: 'Description',
css: {
position: 'absolute',
left: '-99999px'
}
}).prependTo('body'); // element wouldn't be visible for user on this step
//your calculations
$div.remove();
I have created "myCanvas" div element dynamically and try to set styles to the div tag it throw the undefined exception. Please check my code and suggest me
// move the canvas, so it's contained by the same parent as the image
var imgParent = img.parentNode;
$('<div id="myCanvas">');
var can = $('myCanvas');
can.appendTo(imgParent);
// position it over the image
can.style.left = x + 'px'; //If set styles to can element, it's styles is undefined
What i did wrong here.. ? please anyone suggest me a right things..
Thanks,
Bharathi
Make is simple:
$('<div id="myCanvas">').appendTo(img.parentNode).css('left', x);
You don't need to select the myCanvas element because it hasn't been added to the DOM just yet (your selector wasn't right either). You can use this instead:
var imgParent = img.parentNode;
// By default when creating an element in jQuery, it returns an instance of the jQuery object created
var can = $('<div id="myCanvas">');
can.appendTo(imgParent);
can.style.left = x + 'px';
Replace
var can = $('myCanvas');
with
var can = $('#myCanvas');
[edit user="dholakiyaankit"]
QA asking for id not class
Antegias response should read
Replace ... with :
var can = $('#myCanvas');
as you have given it an id not a class, you cant select it in this way till its added to DOM, but you have a reference to it anyway in the variable can
So I'm working on creating a web app that allows users to create a front end theme for a website; I'm mostly doing this to better my JS skills.
What I'm doing in the code below is creating "boxes" that span the width of the page, and I want to allow the user to edit each individual box.
The issue I'm facing is I can select the class/id that the user clicked along with the div I have set up for all the elements that the user wants; however I cannot seem to attach any DOM methods onto the object.
Errors are Uncaught TypeError: Object editBoxes has no method 'innerHTML' where 'innerHTML' can be any method. I've also tried Jquery's .html with the same result.
for(i=1; i <= boxes; i++) {
box.innerHTML = box.innerHTML + [
"<div class = 'globalBox' id = 'box"+i+"'>",
"<div class = 'editDyBox'>edit this box <div class = 'editBoxes'></div<!--end edit boxes--></div>",
"</div><!--end box-->",
].join('');
}//end for
$(".globalBox").css("width", width+"%");
$(".editDyBox").click(function(){
var parentClass = $(this).parent().attr("id");
var childClass = $(this).children().attr("class");
var customEdit = $(this).attr("class");
var editBoxForm = "<form class = 'editBoxForm'><input type = 'text' name = '"+parent+"' width = '100%'></form>";
childClass.innerHTML("hello")
});//end editdybox click
Thank you
-Art
Why don't you use contenteditable instead of your complex code?
It's designed for that.
Check out this Demo
<div contenteditable="true">I'm the content</div>
It's supported by ALL browsers (yeah, even IE5)
its a normal div, so it spans all the available width, and his content is editable. No JS or CSS nedded.
This line returns a string, not a jQuery object
var childClass = $(this).children().attr("class");
So your variable childClass is going to just be a simple string object. It will never have the method innerHTML.
Additionally, this will return only the first child's class value and not an array of class values.
What about using one click handler per element?
var boxes = 3;
var $boxes = $("#boxes");
$.each(new Array(boxes), function () {
var box = $("<div/>").appendTo($boxes),
editBox = $("<div/>").text("edit this box").appendTo(box),
editBoxForm = $("<div/>").appendTo(editBox);
editBox.click(function () {
editBoxForm.html("hello");
});
});
jsFiddle Demo
Remove this
childClass.innerHTML("hello")
By this
$(this).children().innerHTML("hello");
I am making a plugin for form validation as practice, but for some reason after I create a h2 element and try to set it's attribute, it is not working. Here is the code
var testing = function(regex, value, error_msg, error_msg_field_id){
var pattern = new RegExp(regex);
if (!pattern.test(value)){
var ele = document.createElement("H2");
var node = document.createTextNode(error_msg);
ele.setAttribute('style', 'color:white');
alert("hi");
jQuery(error_msg_field_id).append(node);
}
}
the text appears with no problem, but it is not in white color. This make no sense at all to me
You are using setAttribute correctly, but you are setting the property on your h2-element, which is never actually inserted in your DOM.
You can change and simplify the relevant section of your code to:
var ele = document.createElement("H2");
ele.textContent = error_msg;
ele.setAttribute('style', 'color:white');
jQuery(error_msg_field_id).append(ele);
The usage of jQuery here is also not necessary. You can simply use
document.querySelector("#" + error_msg_field_id).appendChild(ele);
which is equally simple.
I figured I would get fancy and use vanilla JavaScript during a jQuery event. The idea is that on click of a heading, I want to slide up a div (which works) and replace the tag clicked on to a larger heading.
From what I've read around, this can be caused by the parentNode referencing an element that's not the actual parent, but after checking it appears to be selecting the element that's directly above it.
So... here's the code!
HTML (in Jade)
.policy-container
h6.policy-heading Policies
.policy-list
.content-we-are-hiding
.not-actually-important
jQuery
$('.policy-heading').click(function() {
var self = this;
if (this.classList.contains('closed')) {
$(this).next().slideDown(300);
this.parentNode.replaceChild(self, '<h6 class="policy-heading">Policies</h6>');
} else {
$(this).next().slideUp(300);
this.parentNode.replaceChild(self, '<h2 class="policy-heading closed">Policies</h2>');
}
});
Everything seems pretty standard. Luckily I can just take care of this with jQuery, however I'd rather be using vanilla JS here. Any ideas why this isn't working?
As has been pointed out, replaceChild takes two nodes.
The following will work with native JS wrapped inside jQuery, as you've specified:
$('.policy-heading').click(function () {
var self = this,
h2 = document.createElement('h2'),
h6 = document.createElement('h6');
h2.class = "policy-heading closed";
h2.innerHTML = "Policies";
h6.class = "policy-heading";
h6.innerHTML = "Policies";
if (this.classList.contains('closed')) {
$(this).next().slideDown(300);
this.parentNode.replaceChild(h6, self);
} else {
$(this).next().slideUp(300);
this.parentNode.replaceChild(h2, self);
}
});
replaceChild takes two nodes, you are giving it a node and a string.
It looks like you'd be much better off just sticking with jQuery and using toggle functions for the sliding and class change.
try this :
.click(function(this)
you also need some debugging to understand what is going on I would advice you to use :
console.log(this)
use this :
el = document.createElement('h6');
el.class = "policy-heading";
el.innerHTML = "Policies";
this.parentNode.replaceChild(self, el);
As everyone pointed out, .replaceChild accepts two DOM elements, rather than the string like I was using. I also had its arguments backwards, the first is for the new element, the second is the replaced element.
Example code that works
$('.policy-container').on('click', '.policy-heading', function() {
var self = this,
newElement;
if (this.classList.contains('closed')) {
newElement = document.createElement( 'h6' );
newElement.classList.add('policy-heading');
newElement.innerHTML = 'Policies';
} else {
newElement = document.createElement( 'h2' );
newElement.classList.add('policy-heading');
newElement.classList.add('closed');
newElement.innerHTML = 'Policies';
}
$(this).next().slideDown(300, function() {
self.parentNode.replaceChild( newElement, self );
});
});