How to empty the content of a div - javascript

Does someone know how to empty the content of a div (without destroying it) in JavaScript?
Thanks,
Bruno

If your div looks like this:
<div id="MyDiv">content in here</div>
Then this Javascript:
document.getElementById("MyDiv").innerHTML = "";
will make it look like this:
<div id="MyDiv"></div>

If you're using jQuery ...
$('div').html('');
or
$('div').empty();

An alternative way to do it is:
var div = document.getElementById('myDiv');
while(div.firstChild)
div.removeChild(div.firstChild);
However, using document.getElementById('myDiv').innerHTML = ""; is faster.
See: Benchmark test
N.B.
Both methods preserve the div.

If by saying without destroying it, you mean to a keep a reference to the children, you can do:
var oldChildren = [];
while(element.hasChildNodes()) {
oldChildren.push(element.removeChild(element.firstChild));
}
Regarding the original tagging (html css) of your question:
You cannot remove content with CSS. You could only hide it. E.g. you can hide all children of a certain node with:
#someID > * {
display: none;
}
This doesn't work in IE6 though (but you could use #someID *).

In jQuery it would be as simple as $('#yourDivID').empty()
See the documentation.

This method works best to me:
Element.prototype.remove = function() {
this.parentElement.removeChild(this);
}
NodeList.prototype.remove = HTMLCollection.prototype.remove = function() {
for(var i = this.length - 1; i >= 0; i--) {
if(this[i] && this[i].parentElement) {
this[i].parentElement.removeChild(this[i]);
}
}
}
To use it we can deploy like this:
document.getElementsByID('DIV_Id').remove();
or
document.getElementsByClassName('DIV_Class').remove();

you can .remove() each child:
const div = document.querySelector('div.my-div')
while(div.firstChild) div.firstChild.remove()

You can empty your DOM using this:
const el = document.getElementById("MyDiv");
while (el.firstChild) {
el.removeChild(el.firstChild);
}
This is supposed to be faster than the traditionally used method : document.getElementById("MyDiv").innerHTML = "";

Related

Add an <br> or <p> with createElement

How can i add an createElement(br) before and after the table? I tried it with doc.body.appendChild(p); at the end, but nothing happens. i don't know where i have to write the appendchild
function insertBlock(border)
{
var doc = document.getElementById("frame").contentWindow.document;
var p = doc.createElement("br");
var range = doc.getSelection().getRangeAt(0);
myParent=document.getElementById("frame").contentWindow.document.body;
if (border == true)
{
myTable=document.createElement("table");
myTable.setAttribute("style","border: 1px solid #000000;");
}
else
{
myTable=document.createElement("table");
}
// IE5, IE6 benoetigen unbedingt tbody-Element
myTBody=document.createElement("tbody");
myRow=document.createElement("tr");
myCell=document.createElement("td");
myText=document.createTextNode("Die erste Zelle");
myCell.appendChild(myText);
myRow.appendChild(myCell);
myCell=document.createElement("td");
myText=document.createTextNode("Die zweite Zelle");
myCell.appendChild(myText);
myRow.appendChild(myCell);
myTBody.appendChild(myRow);
myTable.appendChild(myTBody);
myParent.appendChild(myTable);
range.insertNode(myTable);
}
Should be here:
myParent.appendChild(p);
myParent.appendChild(myTable);
myParent.appendChild(p.cloneNode());
Notice that the second one is a clone. When it's not. Only the second one will be added. (You can not add an element twice).
You can also add two different objects of course.
myParent.appendChild(p);
myParent.appendChild(myTable);
myParent.appendChild(p2);
Or withoud variables:
myParent.appendChild(doc.createElement("br"));
myParent.appendChild(myTable);
myParent.appendChild(doc.createElement("br"));
Try this:
myTable.insertAdjacentHTML('afterend','<br />');
myTable.insertAdjacentHTML('beforebegin','<br />');
if you want to do it using createElement('br').
var p = doc.createElement("br");
myParent.insertBefore(p,myTable);
myParent.insertBefore(p.cloneNode(),myTable.nextSibling);

Adding class to all childrens(in first level o hierarchy) of specified element in javascript without jquery

I want to change this from jquery to javascript:
$('#id_of_element').children('div').addClass('some_class');
So far all i have is this(not working):
document.getElementById('id_of_element').getElementsByTagName('div').addClass('some_class');
I have to change all my code from jquery to javascript. Is there any site with have examples of functions in javascript next to jquery? Thanks in advance for all help :)
Try
var el = document.getElementById('elem'),
//modern browsers IE >= 10
classList = 'classList' in el;
for (var i = 0; i < el.children.length; i++) {
var child = el.children[i];
if (child.tagName == 'DIV') {
if (classList) {
child.classList.add('test');
} else {
child.className += ' test'
}
}
}
Demo: Fiddle
If anyone wants to loop through all children, this worked for me:
const addClassList = (element) => {
Object.values(element.children).forEach((e) => {
e.classList.add('myClass');
if (e.children.length > 0) addClassList(e);
});
};
addClassList(myElement);
NOTE:
Does not work with conditional rendering
Remove the hash(#): in javascript you don't need to use # when selecting id.
document.getElementById('id_of_element').getElementsByTagName('div').addClass('some_class');

jQuery javascript way of checking if some html exist on page

Before appending more code, I want to make sure:
<a href='index.php?option=com_content&view=article&id=36'>Hello</a>
isn't already on the html page inside the div where id='faqs'
<div id='faqs'>
<a href='index.php?option=com_content&view=article&id=36'>Hello</a>
</div>
What is the best way of doing this with jquery or javascript?
Thanks
The easiest way would be to use jQuery to select the element, and check the length property of the resulting object:
var anchor = $('#faqs a[href="index.php?option=com_content&view=article&id=36"]')
if(anchor.length == 0) {
// element isn't on the page
}
You could search using indexOf
var inBlock = $('#faqs').html();
if (inBlock.indexOf("<a href='index.php?option=com_content&view=article&id=36'>Hello</a>") == -1) {
$('#faqs').append ("<a href='index.php?option=com_content&view=article&id=36'>Hello</a>");
}
if (!$('a[href$="view=article&id=36"]', '#faqs').length) {
//does'nt exist
}
If the goal is to end up with the a tag as a child in the div tag, and thats it, then don't bother checking, just re add it, like this:
$('#faqs').html('');
$('<a />')
.attr('href', 'index.php?option=com_content&view=article&id=36')
.html('hello')
.appendTo($('#faqs'))​;​
However, if you genuinely need to check if it exists, then you can do something like this:
var exists = $('#faqs a[href="index.php?option=com_content&view=article&id=36"]').length > 0;
UPDATE
Finding the string in the html can be done as follows, but this is not a recommended solution. You may run into issues with different browsers encoding html in different ways etc (tested in chrome):
var stringToFind = 'Hello';
// need to replace the & ...
stringToFind = stringToFind.replace(/&/g, '&');
var exists = $('#faqs').html().indexOf(stringToFind) > -1;
if (exists) {
// do something
} else {
// do something else
}
Here's a working example -> http://jsfiddle.net/Uzef8/2/

change backround image of another div when hovering over list item

I have a list in a div and I would like to change the background image of the parent div (#homepage_container) when I hover over a list item.
here's the site:-
http://www.thebalancedbody.ca/
Is this possible? I'm guessing I'll have to use javascript.
Thanks
Jonathan
This is quite simple with pure javascript.
function changeBg(newBg)
{
var imgdiv = document.getElementById("divwithbackground");
imgdiv.style.backgroundImage = "url(" + newBg + ")";
}
Or using sprites:
imgdiv.style.backgroundPosition = "new position";
This can be executed on mouseover for any of your li's. Event registration in javascript can be done many ways, but to do it in script, I recommend QuirksMode's method here.
Something like:
function addEventSimple(obj,evt,fn) {
if (obj.addEventListener)
obj.addEventListener(evt,fn,false);
else if (obj.attachEvent)
obj.attachEvent('on'+evt,fn);
}
And on load:
// get the list items
var ul = document.getElementById("ulId");
var lis = ul.getElementsByTagName("li");
// add event handlers
for (var i = 0; i < lis.length; i++)
{
addEventSimple(lis[i], "mouseover", (function(j) {
return function() {
// get your background image from the li somehow
changeBg(lis[j].id + "_bg.png");
};
})(i)); // use a closure to capture the current value of "i"
}
You have to use JS.
Better to learn something like jQuery.
With it you will have to do something like
var images = ['img1.jpg', 'img2.jpg', ...]
for (var i = 0; i < li_count; ++i) // li_count is the number of li's
$('li:eq(' + i + ')').mouseover(function() {$('#homepage_container').css('background-image', images[i]})
Anyway, if you wish to use such kinds of techniques, you have to learn JS.
See http://www.w3schools.com/js/default.asp and for basics and http://docs.jquery.com/Tutorials for jQuery.
I suggest installing the Jquery Library for this (jquery.com)
Just add this to your header:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js">
<script type="text/javascript">
$(document).ready(function() {
$('li').hover(function(){
$('#homepage_container').css('background-image' : 'whatever.png');
}
});
</script>
If you don't care about IE6, you could do it with CSS:
#homepage_container { background: url(normal.png); }
#homepage_container:hover { background: url(hover.png); }

Javascript DOM howto?

I am a javascript noob.
I would like to select the second 'p' element of the div.box.
How do I do this?
Thanks a lot!
Tom
To get second p element of div with class box you'd do this:
var paragraph = null;
var divs = document.findElementsByTagName('div');
for (var i = 0; i < divs.length; i++) {
var div = divs[i];
if (div.class == 'box') {
var paragraphs = div.getElementsByTagName('p');
if (paragraphs.length > 1)
paragraph = paragraphs[1];
break;
}
}
The paragraph would then be in the paragraph variable (or null if it wasn't found).
However you can do this much easier with a library such as jQuery:
var paragraph = $('div.box p:eq(1)');
Without using jQuery, the basic method would be to attach an unique ID to your Dom element
<p id="second_p_elmt"> [...] </p>
and then accessing it through the getElementById() method:
<script ...>
var second_p_elmt = document.getElementById('second_p_elmt');
</script>
<script type="text/javascript">
var boxElem = document.getElementById('box'),
pElems = boxElem.getElementsByTagName('p'),
whatYouWant = pElems[1]; // [1] is the second element in the response from getElementsByTagName
</script>
You have several options. As stated above, you could use one of the excellent frameworks, like jQuery or prototype. Or you give the <p/> an ID, that you can use simply with document.getElementById().
Then, as reko_t pointed out, without the above, you must write a lengthy DOM traversing code (which is preferable, if you don't use JS frameworks elsewhere, over embedding them only for this task).
In the most recent browsers (namely, IE>=8, FF>=3.5, recent Opera and Safari > 3) you can also use this simple snippet:
var p = document.querySelectorAll("div.box p");

Categories

Resources