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>
.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>