Ganesh Pokale
Ganesh Pokale

Reputation: 1594

Click li element JavaScript Programmatically

Click li element "Last 30 days" programmatically (console)

<div class="ranges">
      <ul>
        <li>Today</li>
        <li >Yesterday</li> 
        <li>Last 7 days</li>
        <li>Last 30 days</li>
        <li class="">This month</li>
        <li>Custom Range</li>
    </ul>
  </div>

I tried many way but failed

Like.

$('#Last 30 days').trigger('click');
$('#Last 30 days').click();

I'm new in JavaScript Please help me

Upvotes: 4

Views: 10888

Answers (3)

Kamil Kiełczewski
Kamil Kiełczewski

Reputation: 92347

try

myLiElement.click();

myLiElement.click();

// this is for TEST
function clicked() { console.log('clicked!') }
<div class="ranges">
  <ul>
    <li>Today</li>
    <li>Yesterday</li>
    <li>Last 7 days</li>
    <li id="myLiElement" onclick="clicked()">Last 30 days</li>
    <li class="">This month</li>
    <li>Custom Range</li>
  </ul>
</div>

Upvotes: -1

dgc
dgc

Reputation: 565

What you have here looks like jQuery (or something modeled on jQuery) — not pure, natural JavaScript. I mention this just for completeness and for proper tagging.

That said, and assuming that you actually have jQuery loaded, this is failing because your selectors aren't matching anything. $('#...') matches DOM elements by ID. You don't have any IDs. This would work:

<div class="ranges">
  <ul>
    <li>Today</li>
    <li >Yesterday</li> 
    <li>Last 7 days</li>
    <li id="target">Last 30 days</li>
    <li class="">This month</li>
    <li>Custom Range</li>
  </ul>
</div>
<script>
  $('#target').click();
</script>

CSS does not address elements by content, and neither does jQuery. You could find a way to implement it, but it would be horribly inefficient (which is why it's not built in). If you have the option, it's better just to identify each <li>.

You can also target by class: $('.classname'). But while targeting by ID will typically only hit one element, targeting by class will hit all matching elements.

I also note that you don't appear to have any actions attached to the click event on the <li> elements, so I'm not sure that you would notice whether the click event is successful, unless there's more to your situation than you've described.

Upvotes: 1

Josh
Josh

Reputation: 1474

Trigger the click based on HTML inside.

let listItems = document.querySelectorAll('.ranges li');

listItems.forEach((item, index) => {
  item.addEventListener('click', (event) => {
     alert(`${event.currentTarget.innerHTML} item was click`);
  });
  if (item.innerHTML.indexOf('Last 30 days') != -1) {
      item.click();
  }
});
<div class="ranges">
    <ul>
      <li>Today</li>
      <li>Yesterday</li> 
      <li>Last 7 days</li>
      <li>Last 30 days</li>
      <li>This month</li>
      <li>Custom Range</li>
  </ul>
</div>

Upvotes: 7

Related Questions