Pass 'div' element as parameter to JavaScript function - javascript

I need to create, decorate and append child 'divs' to existing. For example, after the appendChildren is executed, following divs
<div id="a">
<div id="b">
</div>
</div>
should take the following form (assuming decorateDiv adds text "This is new div" inside new div)
<div id="a">
<div id="b">
<div>"This is new div"</div>
</div>
<div>"This is new div"</div>
</div>
Here is my code
function appendChildren() {
var allDivs = document.getElementsByTagName("div");
for (var i = 0; i < allDivs.length; i++) {
var newDiv = document.createElement("div");
decorateDiv(newDiv);
allDivs[i].appendChild(newDiv);
}
}
function decorateDiv(div) {
var x = document.getElementByTagName("div");
var t = document.createTextNode("This is new div");
x.appendChild(t);
}
I am completely new to JavaSpript. What am I doing wrong? Please help me to fix bugs

You're not using the parameter div and the decorateDiv should look like this:
function decorateDiv(div) {
//div is the object element
var t = document.createTextNode("This is new div");
div.appendChild(t);
}

The parameter 'div' that you are passing to function 'decorateDiv' has nowhere been used.
You can change your decorateDiv function like as below:
function decorateDiv(div) {
var t = document.createTextNode("This is new div");
div.appendChild(t);
}
Hope this helps!!

"allDivs" variable get update when to appendChild to any div because to stores array of elements of "div" TagName.
So, use class for fetching divs.
<div id="a" class="test">
A
<div id="b" class="test">
B
</div>
</div>
Here is user script:
function appendChildren() {
var allDivs = document.getElementsByClassName("test");
for (var i = 0 ; i < allDivs.length ; i++) {
var newDiv = document.createElement("div");
decorateDiv(newDiv);
allDivs[i].appendChild(newDiv);
}
}
function decorateDiv(div) {
var t = document.createTextNode("This is new div");
div.appendChild(t);
}
appendChildren();
And also you are not using parameter passed to decorative function.
This will work. Try this..

Related

I am having problem with appendChild() while creating new element using createElement("ul")

I am having problem creating UL and LI below the P tag. Can someone take a look at my codes below? The javascript is returning the following error:
Uncaught TypeError: thisIsQuizContainer.appendChild is not a function
Changing it to document.body.appendChild() will create the UL in the body. How do i create the UL inside the div quizMainContainer?
This is the HTML:
<div id="quizMainContainer">
<h2>Question 1 of 3:</h2>
<p id="quizQuestion"></p>
<!-- create UL here -->
</div>
This is my Javascript.
var ulCreate = document.createElement("ul");
var thisIsQuizContainer = document.querySelectorAll('#quizMainContainer');
function render(questionIndex) {
// Clears existing data
questionsDiv.innerHTML = "";
ulCreate.innerHTML = "";
thisIsQuizContainer.innerHTML = "";
// For loops to loop through all info in array
for (var i = 0; i < questions.length; i++) {
// Appends question title only
var userQuestion = questions[questionIndex].title;
var userChoices = questions[questionIndex].choices;
questionsDiv.textContent = userQuestion;
}
// New for each for question choices
userChoices.forEach(function (newItem) {
var listItem = document.createElement("li");
listItem.textContent = newItem;
thisIsQuizContainer.appendChild(ulCreate);
ulCreate.appendChild(listItem);
listItem.addEventListener("click", (compare));
})
}
document.querySelectorAll('#quizMainContainer') // nodelist [{},{},{}]
which select list of elements from the dom, I suggest you use
document.getElementById('#quizMainContainer') // node element

dynamically add EventListener doesn't work as expected

When I try to dynamically fill a wrapper element with HTML elements, and then add an EventListener for that element, it only uses the last value.
window.onload=function(){
sW="";
for(var i = 0; i < 5; i++) {
var e = document.createElement('div');
e.innerHTML = "test div number "+i;
e.addEventListener('click', function() {alert("t:"+i);});
document.getElementById('wrap').appendChild(e);
}
}
<html>
<body>
<div id="wrap"></div>
</body>
</html>
That's because var keeps the the reference to the variable. Use let instead.

innerHTML strips classes?

I have a div with HTML, that I am trying to push inside an empty div. The new div should acquire all the content and styling from the original.
Existing content:
<ul id="existing_id" class="my_class">
<strong>Does not show up in new div</strong>
<li class="style">
<p class="style">Shows up in new div</p>
</li>
</ul>
New, empty div - where I push everything from "existing_id" into:
<div id="empty_div"></div>
I am targeting the elements through JS:
var existing = document.getElementById("exisiting_id")
var existing_li = existing.getElementsByTagName("li")
var empty_div = document.getElementById("empty_div")
var myArray = []
empty_div.innerHTML = ""
// Pushing each existing li element inside myArray
for (var i=0; i < existing_li.length; i++) { myArray.push(existing_li[n]; }
function make_it_happen() {
empty_div.innerHTML += myArray.innerHTML
}
I am getting the content from #existing_id inside the new div - but not the styling associated with each element. Some elements are also ignored such as <strong>Does not show up in new div</div>
If you are wanting to collect all of the HTML from all of the LI elements into empty_div, you don't need myArray. The following should do:
var existing = document.getElementById("existing_id")
var existing_li = existing.getElementsByTagName("li")
var empty_div = document.getElementById("empty_div")
function make_it_happen() {
var html = '';
for (var i = 0; i < existing_li.length; i++) {
html += existing_li[i].innerHTML;
}
empty_div.innerHTML = html;
}

How do you use Javascript to add or remove HTML/CSS code?

If I have a bunch of HTML code, similar to the following:
<div id='test0div'>
<p id='test0'></p>
</div>
How do I use JavaScript to add or remove more of those - i.e.
<div id='test1div'>
<p id='test1'></p>
</div>
<div id='test2div'>
<p id='test2'></p>
</div>
...etc.?
var container = document.createElement("div");
for(var i=0; i<5; i++) { // change i <5 as per your data source
var div = document.createElement("div");
var p = document.createElement("p");
p.id = "test"+i;
div.id = "test"+i+"div";
div.appendChild(p);
container.appendChild(div); // you can event append to particular id or body
}
// document.getElementById("divId").appendChild(container);
container, will have all the divs & p as you wish
This will give you the output you want. Just change the number of times the loop will execute based on your wish.
To remove you could use
$('#id').remove();
To add you could use
$("<div id='new'></div>").appendTo('#id');

remove this.class function Javascript

I have a function connected to a class, that lets me remove it by className.
the problem I have is when I have two elements with the same class name. the function close both of the classes and not only the one that's selected.
I think that i use use a element.this function, but when I try it, none of the classes removes.
Any ideas ?
function CloseEvent(){
var CloseEvent = "close";
var addClassArr= document.getElementsByClassName(CloseEvent);
for(var i=0; i<addClassArr.length; i++){
var addClass = addClassArr[i];
addClass.addEventListener("click", closebutton, true);
}
function closebutton() {
var classToRemove = "dice-window-wrapper";
var elems = document.getElementsByClassName(classToRemove);
for (var i = 0; i < elems.length; i--) {
elems[i].parentNode.removeChild(elems[i])
}
}
}
CloseEvent();
the function close both of the classes and not only the one that's selected.
That's wrong, since more than one are selected via document.getElementsByClassName - and all of them are removed correctly.
Instead of selecting elements by their class name, select the one on which the event was fired at.
function closebutton(e) {
var elem = e.target; // or just the "this" keyword
// elem is the <div class="close" />
var wrapper = elem.parentNode.parentNode;
// wrapper is the <div class="dice-window-wrapper" />
wrapper.parentNode.removeChild(wrapper);
}
Updated the html code to reflect the html used on your site.
<div class="dice-window-wrapper">
<div class="dice-menubar-wrapper">
<div class="close">
close one
</div>
</div>
</div>
<div class="dice-window-wrapper">
<div class="dice-menubar-wrapper">
<div class="close">
close one
</div>
</div>
</div>
then here is how to remove the clicked element:
function CloseEvent(){
var CloseEvent = "close";
var addClassArr= document.getElementsByClassName(CloseEvent);
for(var i=0; i<addClassArr.length; i++){
var addClass = addClassArr[i];
addClass.addEventListener("click", closebutton, true);
}
function closebutton(e) {
var classToRemove = " "+"dice-window-wrapper"+" ";
var obj=e.target;
while((" "+obj.className+" ").indexOf(classToRemove)==-1){
obj=obj.parentNode;
}
if(obj.tagName.toLowerCase()!="div"){
console.log("something wrong in closebutton");
return;
}
obj.parentNode.removeChild(obj);
}
}
Note that this doesn't work at all in IE8 because getElementsByClassName is not supported not is the event passed in this way and there might be a problem with addEventListner. That's why I usually use jQuery.
You should be able to identify the object calling a JS function by using this to identify the triggering element like
function closebutton() {
this.parentNode.removeChild(this);
}
e.g. Delete the SO logo!
function notSO(){this.parentNode.removeChild(this);}
document.getElementById("hlogo").addEventListener("mouseover", notSO, true);
Here's your modified code:
function CloseEvent(){
var CloseEvent = "close";
var addClassArr= document.getElementsByClassName(CloseEvent);
for(var i=0; i<addClassArr.length; i++){
var addClass = addClassArr[i];
addClass.addEventListener("click", function(){ closebutton(this) }, true);
}
function closebutton( elem ) {
var classToRemove = "dice-window-wrapper";
//var elems = document.getElementsByClassName(classToRemove);
//for (var i = 0; i < elems.length; i--) {
// elems[i].parentNode.removeChild(elems[i])
//}
// you have passed the element to be removed, directly remove it
elem.parentNode.removeChild(elem);
}
}
CloseEvent();

Categories