let n = 5; let m = 5; for(let j=0; j<m; j++){ for(let i=0; i<n; i++){ let boite = document.createElement("p"); boite.innerHTML = i+1; document.querySelector("body").appendChild(boite); } document.write("<br>"); }
body{ margin: 20px; background-color: white; } p{ background-color: black; color: white; padding: 20px; width: 30px; border: 2px solid white; display: inline-block; }
I'm trying to change the background-color
of a paragraph in yellow when the number is even (so, in javascript ).
I believe i have to write a condition with as a result something like
document.body.style.backgroundColor = "yellow";
but i don't know how to select the paragraph as i don't want the backgroundColor
of the body
to change
只需给每个段落一个单独的 id,然后获取元素的 id,然后像这样更改它的样式: document.getElementById("ID").style.backgroundColor = "yellow";
To change the bacgkround color of a paragraph just use following:
<body>
<p id="paragraphToChange">Hello World!</p>
<script>
document.getElementById("paragraphToChange").style.background = "blue";
</script>
</body>
You can do this using a condition as follows
if((i+1)% 2 == 0){}
let n = 5; let m = 5; for(let j=0; j<m; j++){ for(let i=0; i<n; i++){ let boite = document.createElement("p"); boite.innerHTML = i+1; if((i+1)% 2 == 0){ //voir si i+1 est pair ajouter le couleur boite.style.backgroundColor = "yellow"; boite.style.color = "#000"; } document.querySelector("body").appendChild(boite); } document.write("<br>"); }
body{ margin: 20px; background-color: white; } p{ background-color: black; color: white; padding: 20px; width: 30px; border: 2px solid white; display: inline-block; }
Here's how I'd do it:
let docBody = document.querySelector("body"); let n = 6; let m = 6; for (let j = 1; j < m; j++) { for (let i = 1; i < n; i++) { ifEven = (!(i % 2)) ? "style='background-color:yellow;color:#000;'" : ""; docBody.insertAdjacentHTML("beforeend", "<p " + ifEven + ">" + i + "</p>"); } docBody.children[docBody.children.length - 1].insertAdjacentHTML("afterend", "<br>"); }
body { margin: 20px; background-color: white; } p { background-color: black; color: white; padding: 20px; width: 30px; border: 2px solid white; display: inline-block; }
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.