search

Home  >  Q&A  >  body text

Using JQuery to trigger a click event only when a specific character appears in a paragraph

I have an accordion with some text marked "Important". I want the page to automatically open pages marked "Important" by clicking a button toggle when the page loads.

I've used $(".diff__filename:contains('sections/')")) to search for the word "Important" in the title, but I don't know how to tell it to click the button next to it .

I chose to use JQuery to avoid looping through class names.

<p class="title">
  Important: Content 1
  <button class="toggle">Open</button>
</p>
<p class="title">
  Content 2
  <button class="toggle">Open</button>
</p>
<p class="title">
  Content 3
  <button class="toggle">Open</button>
</p>
<p class="title">
  Important: Content 4
  <button class="toggle">Open</button>
</p>

P粉269530053P粉269530053275 days ago476

reply all(1)I'll reply

  • P粉717595985

    P粉7175959852024-02-18 09:15:59

    You can use :contains on an element and then trigger a click:

    $('document').ready(function() {
    
      $('button').click(function() {
        let name = $(this).data('name');
        console.log('click on:', name);
      });
    
      $('div p:contains("Important")').find('button').trigger('click');
    
    });
    sssccc
    

    Important: Content 1

    Content 2

    Content 3

    Important: Content 4

    Load output:

    click on: Button 1
    click on: Button 4

    reply
    0
  • Cancelreply