nth
nth

Reputation: 45

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..

Upvotes: 0

Views: 50

Answers (2)

Ty Kroll
Ty Kroll

Reputation: 1395

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>

Upvotes: 2

Mahmoud Zakal
Mahmoud Zakal

Reputation: 128

is this what you really want to do

for (var i = 0;i< li;i++){
        var item=document.getElementsByTagName("li")[i].setAttribute("class", "color")
 document.getElementById("goster").children[0].children[i].textContent=name[item];
}

Upvotes: 0

Related Questions