0

I have a variable that contains html code.

var link = "<li><a href="#"></a></li>";

I want to color my element a which is repeat n times. So I did : document.getElementsByTagName("a").addClass("selected")

And in my css I defined

.selected{ color: red; }

But it seems to not work. Nothing changed in the html.

LovePoke
  • 45
  • 1
  • 8
  • Welcome to Stack Overflow, your question should contain [a Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve). – hungerstar Dec 07 '17 at 17:47
  • `addClass()` is not a native dom method. Please open your browser console and look at errors thrown. Big clues there! – charlietfl Dec 07 '17 at 17:48
  • 1
    Hint: Look at the syntax... You are terminating the string prematurely. You should use: `var link = "
  • ";` – Fusseldieb Dec 07 '17 at 17:49
  • 1
    `getElementsByTagName` gives you a collection of DOM elements (even if it's a collection of one) so you would need to iterate through the collection and apply the class to each item. Also, `addClass()` is a jQuery method, the vanilla JS way is to use `.classList()` (e.g. `elem.classList.add('selected')`). – delinear Dec 07 '17 at 17:49
  • 1
    Aaand... If you use ByTagName you must specify *which* tag in the DOM collection. So it should be: `document.getElementsByTagName("a")[0].addClass("selected");` for the first tag, `[1]` for the second, `[2]` for the third... – Fusseldieb Dec 07 '17 at 17:50
  • 1
    Are the contents of `link` event rendered in the document...??? – Jerome Indefenzo Dec 07 '17 at 18:17
  • `getElementsByTagName( 'a' )` will return **all** `` on the page! Not just the ones in a certain group of `
  • `. Use `querySelectorAll()` with a more specific selector.
  • – hungerstar Dec 07 '17 at 18:51
  • Thanks but nothing worked. :( Maybe I should give you more context. In fact each of my li is fill with the values collected in my array. I have an array [{a:"banana", b:"split"}, {a:"orange", b:"apple"} ...] The li are filled with only the a values.
  • banana
  • orange
  • . I want to color only the li with a certain condition. So I did: for(var i=0; i – LovePoke Dec 08 '17 at 08:40