.innerTextを一回ですませたい
Q&A
Closed
素数判定をしてくれるプログラムです。
以下のコードで理想通り動作はしてくれるのですが、resultText.innerText
の.innerText
を省略できないか試行錯誤していて、以下の2つがその作業中に出た質問です。
質問
- 元々は
let resultText = document.getElementById("result").innerText
として、resultText = "素数です"
のように書いていたのですが、実行しても判定します
部分が変わってくれません。原因は何でしょうか。なお、特にエラーは発生しませんでした。 -
.innerText
部分をどうにか省略できないでしょうか。
わかりづらい質問文ですみません。片方だけでも良いのでどなたかご教授ください。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>素数判定</title>
</head>
<h1>素数判定</h1>
<input id="num" placeholder="自然数を入力">
<button id="submit">決定</button>
<div id="result">判定します</div>
<script>
const judge=()=>{
let n = document.getElementById("num").value;
let resultText = document.getElementById("result");
if(n==2 || n==3){
console.log(n);
resultText.innerText = "素数です";
}else{
for(let i=2;i<=Math.sqrt(n);i++){
if(n%i==0){
console.log(i);
resultText.innerText = "素数です";
}
}
resultText.innerText = "素数ではありません";
}
};
document.getElementById("submit").addEventListener("click",judge,false);
</script>
</html>