0

I can use this to select all the anchor tags in a document, which works great...

var anchors = document.getElementsByTagName('a');

Specifically for replacing "href" functionality with "onclick" (for extending functionality from no javascript, adding thumbnails etc)

Except how can I get it to select just the anchor elements in a certain class of parent element (e.g. pics), leaving the bulk of anchors alone?

<a href="img/TEST/pretty.jpg">ignore me</a>
<div class="pics">
 <a href="img/TEST/testPic1.jpg">1 stuff....</a>
 <a href="img/TEST/testPic2.jpg">2 stuff...</a>
 <a href="img/TEST/TestPic3.jpg">3 stuff..</a>
 ...
 <a href="img/TEST/TestPicN.jpg">n stuff..</a>
</div>

...without additional libraries such as jQuery please!

Here's a quick demo...

function go() {
    var anchorElements = document.getElementsByTagName('a');
    for (var i in anchorElements)
        anchorElements[i].style.backgroundColor = "red";
}
a{background-color:#0F0;}
<a href="img/TEST/pretty.jpg">ignore me</a>
<div class="pics">
 <a href="img/TEST/testPic1.jpg">1 stuff....</a>
 <a href="img/TEST/testPic2.jpg">2 stuff...</a>
 <a href="img/TEST/TestPic3.jpg">3 stuff..</a>
 ...
 <a href="img/TEST/TestPicN.jpg">n stuff..</a>
</div>
<button onclick="go()">Go!</button>

I know a workaround is just to select by a class applied to the elements that need modifying

2
  • 1
    you can do it with DOM selector easily Commented Jul 2, 2018 at 23:28
  • 1
    Not all A elements are links, you can get all the links using document.links. ;-) Commented Jul 2, 2018 at 23:58

1 Answer 1

1

Use querySelectorAll('.pics a') to select a collection of <a> under .pic class

function go() {
    var anchorElements = document.querySelectorAll('.pics a');
    for (var i in anchorElements)
        anchorElements[i].style.backgroundColor = "red";
}
a{background-color:#0F0;}
<a href="img/TEST/pretty.jpg">ignore me</a>
<div class="pics">
 <a href="img/TEST/testPic1.jpg">1 stuff....</a>
 <a href="img/TEST/testPic2.jpg">2 stuff...</a>
 <a href="img/TEST/TestPic3.jpg">3 stuff..</a>
 ...
 <a href="img/TEST/TestPicN.jpg">n stuff..</a>
</div>
<button onclick="go()">Go!</button>

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

3 Comments

Your answer will be much more useful for others if you explain what you changed and why. Please edit your answer.
Enough for my level xD, thanks! Looks like it uses CSS Selectors
It may be much more efficient to add a CSS rule rather than selecting then looping over all the relevant elements one at a time.

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.