【解決方法】div 要素を作成し、この div 要素に class 属性を与えます

プログラミングQA


1. div 要素を作成する
2. この div 要素に、値が「square」の class 属性を指定します。
3. appendChild メソッドを使用して、この div 要素を「squares-wrapper」の ID を持つ要素に追加します。

2. removeSquare という名前の関数を定義します。
この関数は、HTML から「正方形」のクラスを持つ 1 つの要素を削除する必要があります。

私が試したこと:

関数 addSquare(){
let newdiv = document.createElement(“div”);
newdiv.className=”square”
document.getElementsById(“squares-wrapper”).appendChild(newdiv);

}

関数 removeSquare(){
let box= getElementsByClassName(“square”)
box.remove()

解決策 1

この記事で言及されているように:

要素: setAttribute() メソッド – Web API | 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.

「Let」ステートメントについて:

「let」は最新の JS とともに JS に組み込まれ、「void」myVar と同等です。 この var は、宣言のスコープに対して有効です。

let A = 2 ;
is same as :
A = 2 ;

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

削除するには、命令命令を使用して、より短くすることができます:

function removeSquare(){
Document.getElementsByClassName("square")[0].remove() ; // 0 is the index because an Array of Element could be return, instead of one only 'element'.

コメント

タイトルとURLをコピーしました