Home > Blockchain >  Get ID of preceding image on click event
Get ID of preceding image on click event

Time:02-12

I have this HTML code

<div> <img src="download1.jpeg" image-id="9a8ae555af5f"></div>
<div><h1><a href ="#">test</a></h1></div>

When a user clicks on the "test" link, i would like to navigate through the tree and fetch the "image-id" attribute of the image preceding the link

I have tried this but imageID returns undefined

function trackClick(event)
{
  let imageId = this.$('a').prev('img').attr('image-id');

console.log("imageId", imageId);
}

document.addEventListener('click', trackClick, true);

Any ideas on how i can make this work using js or css selectors?

thanks

CodePudding user response:

This is jquery solution with prev() and parent() function:

$('#test').on('click', function() {
    alert($(this).parent().parent().prev('div').find('img').attr('image-id'))
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div> 
  <img src="download1.jpeg" image-id="9a8ae555af5f">
</div>
<div>
  <h1>
    <a href ="#" id = 'test'>test</a>
  </h1>
</div>

CodePudding user response:

Using Vanilla JS, step by step:

function trackClick(event)
{
  let targetElement = event.target || event.srcElement;
     
  let closestDiv = targetElement.closest('div');

  let previousDiv = closestDiv.previousElementSibling;
  
  let insideImage = previousDiv.getElementsByTagName('img');
  // or
  // let insideImage = previousDiv.children;

  console.log(insideImage[0].getAttribute('src'));           
}

document.addEventListener('click', trackClick, true);
  • Related