简体   繁体   中英

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

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>

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.

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM