0

I am facing issue in add attribute to child element in my scenario. Attribute is appending in parent instead of child tag . Please help me in JavaScript.

I have below code in html

  <a href="#">
    <div>dummy</div>
  </a>
</div>

My Javascript is:
-----------------
document.getElementsByClassName('Master')[0].setAttribute('aria-label', 'demo');

Output is:
----------
<div class="Master" aria-label="demo">
  <a href="#">
    <div>dummy</div>
  </a>
</div>

Expected output will be:
-------------------------
<div class="Master">
  <a href="#" aria-label="demo">
    <div>dummy</div>
  </a>
</div>```

2 Answers 2

2

You need to select the specific anchor tag.

document.getElementsByClassName('Master')[0].getElementsByTagName('A')[0].setAttribute('aria-label', 'demo');

Suggest using a class directly in the anchor tag.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks @Tushar Shahi!!. Brilliant solution am getting.
1

You can directly target the specific element (a) using Document.querySelector() that allows CSS like selector:

document.querySelector('.Master a').setAttribute('aria-label', 'demo');

console.log(document.querySelector('.Master a'));
<div class="Master" aria-label="demo">
  <a href="#">
    <div>dummy</div>
  </a>
</div>

If you have multiple elements then use Document.querySelectorAll() and Array.prototype.forEach():

document.querySelectorAll('.Master a').forEach(function(el){
  el.setAttribute('aria-label', 'demo');
});

1 Comment

Thanks @Mamun.. Exact solution you found for me !

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.