0

I have the following script:

<script>
  document.getElementById('myId').classList.add('myClass');
</script>

How to alter it and add myClass into #myId a element? I have single anchor element there:

<div id="myId">
    <a href="#" title="link">Add class to me</a>
</div>
skobaljic
  • 9,379
  • 1
  • 25
  • 51
qwe
  • 47
  • 1
  • 11

2 Answers2

3

According to your question, you want to target the anchor tag and set the class there, so:

var parent = document.getElementById('one');
var anchor = parent.getElementsByTagName("A")[0];
anchor.classList.add('myClass');

That should do it.

If you have multiple anchor tags you can loop through them.

var parent = document.getElementById('one');
var anchorList = parent.getElementsByTagName("A");

for(i = 0; i < anchorList.length; i++) {
    anchorList[i].classList.add('myClass');
}
MrVentzi
  • 639
  • 3
  • 13
  • That's it, but it's still unclear whether the OP has a single or multiple `a` elements. – Felix Kling Apr 16 '15 at 10:32
  • 1
    @MrVentzi +1 Good Answer..Probably You should add Browser Compatibility https://developer.mozilla.org/en-US/docs/Web/API/Element/classList#Browser_compatibility in your answer as well – Sachin Jain Apr 16 '15 at 10:39
  • In case of a single element, this is a bit shorter: `document.querySelector('#one a').classList.add(...)` – Felix Kling Apr 16 '15 at 10:42
-1

to add class name you use

document.getElementById('myId').className="Your class name";