Sam-Bo
Sam-Bo

Reputation: 829

Trigger click on a span

I want to click on a SPAN.show-more automatically. When i click on it shows hidden text. Its ID is a random number something like: SPAN#yui_3_9_1_10_1397969703476_624.show-more I use greaseMonkey. The page is: https://espanol.answers.yahoo.com/question/index?qid=20091125151524AAvxaLo

My wrong code is:

 var i,
 list = document.querySelectorAll(".show-more")
 for (i = 0; i < list.length; ++i) 
 { list[i].click();
 }

Maybe I need to wait until the page is full loaded? Do I need a delay?

Upvotes: 0

Views: 6293

Answers (4)

Dinever
Dinever

Reputation: 690

You can simply call a onclick() event like this:

<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<title>Click</title>
</head>
<body>

<span class="show-none">hello</span>
<span onclick="this.style.backgroundColor = '#f47121'" class="show-more">hello</span>
<span onclick="this.style.backgroundColor = '#128239'" class="show-more">hello</span>

<script type="text/javascript" charset="utf-8">
  var i, list = document.getElementsByClassName("show-more");
  for (i = 0; i < list.length; ++i)
   {
     list[i].onclick();
   }
</script>
</body>
</html>

Upvotes: 1

Chloe Tsui
Chloe Tsui

Reputation: 57

did you try this? with onclick() method

var i, list = document.querySelectorAll(".show-more")
for (i = 0; i < list.length; ++i) 
{
  list[i].onclick();
}

Best regards

Upvotes: 1

Gaurang Tandon
Gaurang Tandon

Reputation: 6753

Though there is a way which you can use:

 element.onclick = function(){ .. };

 if( something )
      element.onclick(); // call the handler

DEMO

Upvotes: 0

Lugia101101
Lugia101101

Reputation: 671

There is no built-in, cross-browser function or method to cause a click. One of the best cross-browser solutions I use if ever needed can be found here. Althrough, if you're trying to cause a function to fire it would be best to just call the function.

As per Luxelin's suggestion, jQuery would be the easiest alternative. When using jQuery $(element).trigger('click') would fire a cross-browser click event on the element.

Upvotes: 0

Related Questions