Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find a class inside another class and do some browser action

I am trying to find a specific class (profileCard) and then check if that class has a different class (followStatus) inside it. If it does have followStatus inside it, I want to click a button which is also inside the profileCard class. here is my code:

var profileCard = document.getElementsByClassName('ProfileCard');
var unfollowButtons = profileCard.getElementsByClassName('button-text');
var followStatus = profileCard.getElementsByClassName('FollowStatus');

for (var i = 0; i < profileCard.length; i++) {
  if (followStatus[i] != null) {
    unfollowButtons[i].click();
  }
}

I want to use this function in Chrome simply pasting it into the console, but the code seemingly does nothing: the button is never clicked. Where is the error in my code and how can I fix that?


1 Answers

It's more convenient to use querySelector method here inside the loop over .profileCards elements:

var profileCards = document.querySelectorAll('.ProfileCard');

for (var i = 0; i < profileCards.length; i++) {
    if (profileCards[i].querySelector('.FollowStatus')) {
        var button = profileCards[i].querySelector('.button-text');
        if (button) {
            button.click();
        }
    }
}
like image 88
dfsq Avatar answered Apr 28 '26 04:04

dfsq



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!