October 22, 2024
Chicago 12, Melborne City, USA
jQuery

Move to next node on click


I’m editing a Tampermonkey script that takes elements from the DOM and makes a new element from those to add them to a different part of the page. The original element has an X button that changes the display value of the div (to style="display: none")

<div id="alertTable">
    <ul>
        <li>Element 0 index 0
        <img src="example.com/img0.jpg">
        <img class="x-close" src="example.com/x_icon.png">
        </li>
    </ul>
</div>
$(document).ready(function newDiv() {
var newElementText = document.querySelector('#alertTable li');
var newElementImg = document.querySelector('#alertTable li img');
var newElementClose = document.querySelector('.x-close');

var newElementCSS = `
<style>
#scriptDiv img {
    width: 500px;
}
#scriptDiv li {
    color: #f8f8f8;
} 
</style>
`;

const HTMLElement = `
<div id="scriptDiv">
${newElementText}
${newElementImg}
${newElementClose}
</div>
`;

$('.DOMheader').prepend(HTMLElement);
});

The issue with that code is that sometimes the <ul> element of the DOM contains more than one element, like so, and the original code only detects and interacts with the first instance of the elements it finds with querySelector (logically)

<div id="alertTable">
    <ul>
        <li>Element 0 index 0
        <img src="example.com/img0.jpg">
        <img class="x-close" src="example.com/x_icon.png">
        </li>
        <li>Element 1 index 1
        <img src="example.com/img1.jpg">
        <img class="x-close" src="example.com/x_icon.png">
        </li>
        <li>Element 2 index 2
        <img src="example.com/img2.jpg">
        <img class="x-close" src="example.com/x_icon.png">
        </li>
    </ul>
</div>

I’d like to modify the original code to listen for the click on the .x-close element, and display the next <li> element’s information on the newElement variables. How could this be achieved? The original code includes this to "close" the DOM’s div when clicking on the injected element’s close button

var DOMClose = document.querySelector('#alertTable.x-close');
var ScriptClose = document.querySelector('#scriptDiv.x-click');

ScriptClose.addEventListener('click', function () {
 DOMClose.click();
}



You need to sign in to view this answers

Leave feedback about this

  • Quality
  • Price
  • Service

PROS

+
Add Field

CONS

+
Add Field
Choose Image
Choose Video