Alejandro Garrido
Alejandro Garrido

Reputation: 529

Select a tag element inside a another element selected by class JavaScript

I have this code and is working

var myClasses = document.getElementsByClassName("myClass");
        for (var i = 0; i < myClasses.length; i++) {
        myClasses[i].innerHTML = "<img src='http://url.com/image'>";
        }

But I need select a element iside myClass element. How can i do this with js?

Thank you!

My html is something like that:

<div class="myClass">
        <span>Span</span>
        <a href="link" rel="nofollow">Content to replace with img</a>
</div>

Upvotes: 1

Views: 1126

Answers (2)

Nenad Vracar
Nenad Vracar

Reputation: 122077

You can use querySelectorAll()

var myClasses = document.querySelectorAll(".myClass a");
for (var i = 0; i < myClasses.length; i++) {
  myClasses[i].innerHTML = "<img src='http://url.com/image'>";
}
<div class="myClass">
  <span>Span</span>
  <a href="link" rel="nofollow">Content to replace with img</a>
</div>

Upvotes: 1

Hitmands
Hitmands

Reputation: 14189

If you don't need to support IE8, you can do it in this way:

document.querySelector('.myClass TAGNAME'); or, if you want select all elements: document.querySelectorAll('.myClass TAGNAME');

Upvotes: 0

Related Questions