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>
7
  • Use document.getElementById('myId').className Commented Apr 16, 2015 at 10:23
  • stackoverflow.com/questions/11444640/… Commented Apr 16, 2015 at 10:25
  • 1
    possible duplicate of How do I add a class to a given element? Commented Apr 16, 2015 at 10:25
  • Is there only a single a element inside #myId? Or are there multiple? Do you want to add the class to all of them? Commented Apr 16, 2015 at 10:30
  • unless you're using jQuery (or any other third party library that supports such bindings), you most likely are forced to iterate through all the <a> elements of your myId dom element, unless you only have a single <a> element in your myId. Commented Apr 16, 2015 at 10:34

2 Answers 2

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');
}
Sign up to request clarification or add additional context in comments.

3 Comments

That's it, but it's still unclear whether the OP has a single or multiple a elements.
@MrVentzi +1 Good Answer..Probably You should add Browser Compatibility developer.mozilla.org/en-US/docs/Web/API/Element/… in your answer as well
In case of a single element, this is a bit shorter: document.querySelector('#one a').classList.add(...)
-1

to add class name you use

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

2 Comments

That doesn't seem to target the OP's issue at all.
This targets the wrong element and overwrites any classes already set.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.