Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you click a button by its inner text in javascript?

Tags:

javascript

I have the following piece of html code:

<div class ="listit">
  <a href="javascript:dB()">Update</a>
  <a href="post.php?f=54&y=5">New iso</a>
  <a href="post.php?f=54&y=2">New check></a>
</div>

The buttons look like that: enter image description here

Now I like to press the button called Update by using its name (but I'm also very interested to see if it works without using its name).

I have already tried to go through the class and collect the names using loop:

var x = document.getElementsByClassName("listit");
for (var i = 0; i < x.length; i++) {
  var counter = x[i].innerText;
  if(counter == "Update"){

  }
}

And I think I almost have it, I just could not find a working way to use that click() function so I click the button Update by name? There is not something like document.getElementByInnerText()? I don't know how to get this work..? :S

like image 667
eyesima Avatar asked Oct 27 '25 11:10

eyesima


2 Answers

You are selecting the surrounding div (which actually has the CSS class listit), not the links inside it.

var x = document.getElementsByClassName("listit");

console.log(x);
<div class ="listit">
  <a href="javascript:dB()">Update</a>
  <a href="post.php?f=54&y=5">New iso</a>
  <a href="post.php?f=54&y=2">New check&gt;</a>
</div>

If you need a collection of the links, use document.querySelectorAll('.listit a'):

function dB() {
  console.log('dB called');
}

const links = Array.from(document.querySelectorAll('.listit a'));

links.forEach((link) => {
  if (link.textContent === 'Update') {
    link.click();
  }
})
<div class ="listit">
  <a href="javascript:dB()">Update</a>
  <a href="post.php?f=54&y=5">New iso</a>
  <a href="post.php?f=54&y=2">New check&gt;</a>
</div>

Sidenote: There are certain characters that need to be replaced by their so-called HTML entities to be usable inside HTML tag content, the most important being these:

&<>

So I replaced your

<a href="post.php?f=54&y=2">New check></a> 

by

<a href="post.php?f=54&y=2">New check&gt;</a>
like image 198
connexo Avatar answered Oct 29 '25 03:10

connexo


You would create a mouseEvent and use dispatchEvent to fire it. (You also need to loop over listit's children, rather than the div itself):

var dB = function() {console.log("CLICKED")}

var x = document.getElementsByClassName("listit")[0].children;
for (var i = 0; i < x.length; i++) {
  var counter = x[i].innerText;
  if (counter == "Update") {
    x[i].dispatchEvent(
      new MouseEvent('click')
    )
  }
}
<div class="listit">
  <a href="javascript:dB()">Update</a>
  <a href="post.php?f=54&y=5">New iso</a>
  <a href="post.php?f=54&y=2">New check></a>
</div>
like image 20
Daniel Beck Avatar answered Oct 29 '25 02:10

Daniel Beck



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!