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:

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
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></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></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></a>
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With