Home > Back-end >  How to access sub-elements in current object within JavaScript/jQuery?
How to access sub-elements in current object within JavaScript/jQuery?

Time:11-03

enter image description here Above I have three banner elements that I want to mark as unread if they are clicked. I structured each banner so that they have a span element within a nested div as shown with the image below (the red dot comes from the span element): enter image description here My javascript for this function is the following code: enter image description here I am trying to add a class ".read-dot" to the ".dot" span element that will hide it. I would like to add this class to the ".dot" span element that is inside the div that the user would click on. Any help would be appreciated.

I tried accessing the this.$(".dot) to access the dot element of the current object that triggered the event, but I now see this syntax is incorrect. I am new to jQuery which is why I tried this; I also could not find the page most relevant to my question on the API doc.

CodePudding user response:

First, you have to remove click accessibility for the child.

$('div.banner > *').css('pointer-events', 'none');

And then, you can use the jquery selector for the .unread class to remove the class and replace .dot with .read-dot

$('.unread').click((e) => {
    let clickedElm = e.target;
    clickedElm.classList.remove('unread');
    clickedElm.querySelector('span').classList.remove('dot');
    clickedElm.querySelector('span').classList.add('read-dot');
    
})
  • Related