Capture URL that is inside a div with Jquery

Asked

Viewed 199 times

0

I have a project where there are several boxes, with an image, and a link. I would like it when I click on the class . single-project captures the value of href, but I’m not getting it.

$('.single-project').on('click', function() {
  window.location.href = ($(this).attr("href"));
});
<div class="single-project">
  <img src="img/project/projeto01.jpg" alt="">
  <div class="project-overly">
    <a href="single-project.html">
      <h3>Titulo</h3>
    </a>
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit.</p>
  </div>
</div>

2 answers

1


From what I understand you need the following code:

$('.single-project').on('click', function() {  
   window.location.href = $(this).find("a").attr("href");
});

If you have multiple Urls

$('.single-project').on('click', function() {
  var arr = [];
  $.each($(this).find('a'), function(index,valor){
   arr.push($(valor).attr('href'))
  });
  $('p').text(arr)
});
  • It worked perfectly, thank you very much man

0

Your problem is the div parent level and the this operator. Put the 'single-project' class in the tag <a> from which you want to extract the URL and where the click is triggered.

 $(document).ready(function() {
     $('.single-project').click(function(){
     	  alert($(this).attr("href"));
     })
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="outra-class">
          <img src="img/project/projeto01.jpg" alt="">
          <div class="project-overly">
            <a class="single-project" href="www.google.com">
              <h3>Titulo</h3>
            </a>
            <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit.</p>
          </div>
        </div>

  • this code does not go right, the action I want is when I click on the box . single-project, because inside it has the link, a description, and an image

  • Then you cannot use this. Then you would use $('a'). attr("href")

  • desa forma aí ele vai pegar o primeiro link que aparece no site

Browser other questions tagged

You are not signed in. Login or sign up in order to post.