1

I'm using jQuery to add a button next to all A>SPAN tags found on a page. The page itself grows as the user scrolls down, which is why I'm using the Scroll function - I need to continually add the button to the new page sections.

The below code continually adds buttons to the sections that already have buttons on them. I'm trying to only show one button next to each found tag combination. I've tried every combination I can think of. I'm hoping someone has an easy solution I can try.

Thank you.

$(window).scroll(function () {
  if (!$("a span button").length) {
    $("a span").after(
      ' <button type="button" class="btn btn-secondary btn-sm">BUTTON</button>'
    );
  }
});
3
  • Please amend the title to something more objective and specific. What exactly is not working? Commented Sep 4, 2022 at 20:00
  • Does this answer your question? jQuery - rule for "does not contain element" Commented Sep 4, 2022 at 23:29
  • @Phil thanks for the correction, how could I forget that? Commented Sep 5, 2022 at 15:10

1 Answer 1

2

jQuery's .after() inserts a sibling element, not a descendant. For example, if you had

<a>
  <span>Text</span>
</a>

the result of your code would be

<a>
  <span>Text</span>
  <button>BUTTON</button>
</a>

This doesn't match your selector "a span button" because the <button> is not a descendant of the <span>.

I would instead add some property or class to the <span> to identify that it has been button-ised, then you can omit those elements in your selections

$(window).scroll(() => {
  $("a span:not(.buttonised)").each((_, span) => {
    $(span)
      .addClass("buttonised")
      .after(
        $("<button>", {
          class: "btn btn-secondary btn-sm",
          text: "BUTTON",
          type: "button",
        })
      );
  });
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.