nth nth - 4 months ago 10
HTML Question

how can create in the combination the codes?

i have 8 li tags.. when i enter name, i want per li tag being green color..but i could not create the combination.. for example when i enter my name, one li tag will be green.. how i can create the combination ?

<style>
.color {
background: green;
}

ul {
list-style: none;
}

li{

width: 100px;
height: 100px;
background: gray;
}
</style>

<div id="goster">
<ul>
<li id="item"></li>
<li id="item"></li>
<li id="item"></li>
<li id="item"></li>
<li id="item"></li>
<li id="item"></li>
<li id="item"></li>
<li id="item"></li>

</ul>

</div>

<script>


var name = prompt("Enter your name:", ""),
li = 8,
item="";
while(++i < li){
var item=document.getElementsByTagName("li")[i].setAttribute("class", "color");
document.getElementById("goster").innerHTML=name[item];
}

</script>


only i need it simply or can u give me any tips .. i tried in loop but it didnt work.. the color should be per enter name as random..

Answer

Not clear what you are actually looking for.

You want to add the .color class to each li after the prompt?

var name = prompt("Enter your name:", "");
var items = document.getElementsByTagName("li");

for(let i = 0; i < items.length; i++) {
  
  let item = items[i];
  
  if(item.className.indexOf('color') < 0) {
    item.className += 'color';
    item.textContent = name;
    break;
  }
}
.color {
        background: green;
    }

    ul {
        list-style: none;
   }

    li {

        width: 100px;
        height: 100px;
        background: gray;
    }
<div id="goster">
  <ul>
    <li></li>
    <li></li>
    <li></li>
    <li></li>
    <li></li>
    <li></li>
    <li></li>
    <li></li>

  </ul>
</div>

Comments