Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

106
Views
Finding the next Canvas id in Jquery

When looking for the next element id in Jquery the simplest solution is to use closest(element). but it is not working for Canvas and I don't know why.

$('a.findNext').click(function() {
  debugger;
  var nextSectionWithId = $(this).closest("canvas").nextAll("canvas[id]:first");
  if (nextSectionWithId) {
    var sectionId = nextSectionWithId.attr('id');
    $("#test").text(sectionId)
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="section_1">
  <a href="#" class="findNext">Find</a>
</div>
<div></div>
<canvas id="section_3"></canvas>
<canvas id="section_4"></canvas>

<div id='test'></div>

Demo : http://jsfiddle.net/jtdgo304/6/

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

.closest will select the nearest ancestor matching the selector. But the .findNext element does not have a canvas ancestor.

If you want to get the next ancestor, you'll need to first navigate to an element that's a sibling of the canvas (which is the #section_1 here), then use .nextAll.

You should also check the .length of the jQuery collection to see if it matches any elements.

$('a.findNext').click(function() {
  const nextSectionWithId = $(this).parent().nextAll("canvas[id]:first");
  if (nextSectionWithId.length) {
    const sectionId = nextSectionWithId.attr('id');
    $("#test").text(sectionId)
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="section_1">
  <a href="#" class="findNext">Find</a>
</div>
<div></div>
<canvas id="section_3"></canvas>
<canvas id="section_4"></canvas>

<div id='test'></div>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!