简体   繁体   中英

Assigning javascript array elements class or id for css styling

I'm trying to assign class and id to items in an array I created in js and input into my html. I'm doing this so I can style them in my stylesheet. Each item will not be styled the same way.

I'm a beginner so trying to keep it to code I can understand and make it as clean as possible, ie not making each of these items an element in the html.

This part works fine:

var pool =['A','B','3','J','R','1','Q','F','5','T','0','K','N','C','R','U']
var letters = pool.join('');
document.getElementById('key').innerHTML = letters; 

This part not so much:

var char1 = letters[1];
char1.classList.add('hoverRed');

There is a similar question here that didn't work for me, it just showed [object][object][object] when I ran it.

Your code attempts to apply a style to an array element, but CSS only applies to HTML. If you wish to style one character in a string, that character must be wrapped in an HTML element (a <span> is the best choice for wrapping an inline value).

This code shows how to accomplish this:

 var pool =['A','B','3','J','R','1','Q','F','5','T','0','K','N','C','R','U'] var letters = pool.join(''); // Replace a specific character with the same character, but wrapped in a <span> // so it can be styled letters = letters.replace(letters[1], "<span>" + letters[1] + "</span>"); // Insert the letters string into the div var theDiv = document.getElementById('key'); // Inject the string into the div theDiv.innerHTML = letters; // Get a reference to the span: var theSpan = theDiv.querySelector("span"); // Add the style to the <span> that wraps the character, not the character itself theSpan.classList.add('hoverRed'); 
 .hoverRed { color:red; } 
 <div id="key"></div> 

And, this snippet shows how you could apply CSS to any letter:

 var pool =['A','B','3','J','R','1','Q','F','5','T','0','K','N','C','R','U']; // Leave the original array alone so that it can be manipulated any way needed // in the future, but create a new array that wraps each array element within // a <span>. This can be accomplished in several ways, but the map() array method // is the most straight-forward. var charSpanArray = pool.map(function(char){ return "<span>" + char + "</span>"; }); // Decide which character(s) need CSS applied to them. This data can come from anywhere // Here, we'll just say that the 2nd and 5th ones should. // Loop through the new array and on the 2nd and 5th elements, apply the CSS class charSpanArray.forEach(function(element, index, array){ // Check for the particular array elements in question if(index === 1 || index === 4){ // Update those strings to include the CSS array[index] = element.replace("<span>","<span class='hoverRed'>"); } }); // Now, turn the new array into a string var letters = charSpanArray.join(''); // For diagnostics, print the string to the console just to see what we've got console.log(letters); // Get a reference to the div container var theDiv = document.getElementById('key'); // Inject the string into the div theDiv.innerHTML = letters; 
 .hoverRed { color:red; } 
 <div id="key"></div> 

You're on the right track, but missed one key thing.

In your example, pool contains characters. When you combine them using join, you get a string. Setting that string as the innerHTML of an element doesn't give the string super powers, it's still just a string.

In order to get a classList, you need to change your letters into elements and work with them.

I've included an es6 example (and a working plunker) of how to get the functionality you want below.

let pool = ['A','B','3','J','R','1','Q','F','5','T','0','K','N','C','R','U']

const letterToElement = function(char) {
  //Create the element
  let e = document.createElement("SPAN");

  //Create the text node
  let t = document.createTextNode(char);

  //Put the text node on the element
  e.appendChild(t);

  //Add the class name you want
  e.className += "hoverRed";
  return e;
};

//create your elements from your pool and append them to the "key" element
window.onload = function() {
  let container = document.getElementById("key");
  pool.map(l => letterToElement(l))
      .forEach(e => container.appendChild(e));  
}

https://plnkr.co/edit/mBhA60aUCEGSs0t0MDGu

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM