Click here to Skip to main content
16,017,788 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
1. Create a div element
2. Give this div element a class attribute with a value of "square"
3. append this div element using the appendChild method to the element with the id of "squares-wrapper"

2. Define a function named removeSquare.
This function should remove one element with the class of "square" from the HTML.

What I have tried:

function addSquare(){
let newdiv = document.createElement("div");
newdiv.className="square"
document.getElementsById("squares-wrapper").appendChild(newdiv);


}


function removeSquare(){
let box= getElementsByClassName("square")
box.remove()
Posted
Updated 2-May-23 4:43am
Comments
Dave Kreskowiak 2-May-23 8:49am    
You forgot to ask a question.

as mention in this article :

Element: setAttribute() method - Web APIs | MDN[^]

JavaScript
function ADD_ELM( new_tag, id_target , attr , attr_value ){

newElm = document.createElement(" + new_tag + ") ;

newElm.setAttribute( attr , attr_value ) ;

document.getElementById( id_target ).appendChild( newElm ) ;

}

ADD_ELM( "DIV" , "squares_wrapper" , "class" , "square" ) ; // function ADD using.



About "Let" statement :

'let' comes in JS with the modern JS, and is equal : 'void' myVar. this var is alive for the scope of the declaration.
let A = 2 ;
is same as :
A = 2 ;

// Once out of the scope, this var is delete.



to remove you can do shorter, with an imperative instruction :

function removeSquare(){
Document.getElementsByClassName("square")[0].remove() ; // 0 is the index because an Array of Element could be return, instead of one only 'element'.
 
Share this answer
 
Comments
Dave Kreskowiak 2-May-23 8:49am    
Learn to recognize a homework assignment and don't do their homework for them.
adla099 2-May-23 9:43am    
Hi, thanks for your solution. I tried it but got "Error: Exception: Cannot read property 'appendChild' of null"
adla099 2-May-23 10:40am    
i tried a different way. this worked.I was just supposed to get the Id element first


function addSquare(){
let wrapper=document.getElementById("squares-wrapper");
let newElm= document.createElement("div") ;
newElm.classList.add("square");
wrapper.appendChild(newElm);
}

function removeSquare(){
let erase= document.getElementsByClassName("square")[0]
erase.remove()
}
function addSquare(){
let wrapper=document.getElementById("squares-wrapper");
let newElm= document.createElement("div") ;
newElm.classList.add("square");
wrapper.appendChild(newElm);
}

function removeSquare(){
let erase= document.getElementsByClassName("square")[0]
erase.remove()
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900