Home > front end >  If there is such a content, append it to the next element
If there is such a content, append it to the next element

Time:11-26

I am checking content and I want to add button to right of button.

Following my code:

jQuery(document).ready(function(){
    jQuery('.btn-click').click(function(){
        $("p:contains(Test 2)").find('.view').append('<button>View-2</button>');

    });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  <button class="btn-click">Click Me</button>
  <p>Test 1</p> <button class="view">View</button>
  <p>Test 2</p> <button class="view">View</button>
  <p>Test 3</p> <button class="view">View</button>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

Since the button is not a child of your p then you have to use .next('.view') and not .find('.view')

Demo

Show code snippet

jQuery(document).ready(function() {
  jQuery('.btn-click').click(function() {
    $("p:contains(Test 2)").parent().find('.view').append('<button>View-2</button>');
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="btn-click">Click Me</button>
<div>
<p>Test 1</p> <span>Test Span</span> <button class="view">View</button>
</div>
<div>
<p>Test 2</p> <span>Test Span</span> <button class="view">View</button>
</div>
<div>
<p>Test 3</p> <span>Test Span</span> <button class="view">View</button>
</div>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related