JsStorm2
JsStorm2

Reputation: 75

get a href attribute and set this attribute to other div

I have 3 classes with such a structure (this is slider in my web app):

<div class="emotion--digital-publishing">
  <div class="dig-pub">
    <div class="bg--image">/div>
      <div class="dig-pub--layer center center">
        <div class="layer--wrapper">
          <div class="layer--content">
            <div class="dig-pub--button">
              <a href="/wilson-camo"></a>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>

I want to get href attribute of a and set a href atribute with this url to dig-pub. It is very important to me that this is the link (which class I clicked), because 3 classes have different links. I would like to use jQuery.

Upvotes: 0

Views: 203

Answers (3)

Kidkie
Kidkie

Reputation: 83

(Don't forget to close the div on line 3 in your snippet)

jQuery('.dig-pub').on('click', function() {
   url = jQuery(this).parent().find('a').attr('href');
   jQuery(location).attr(url);
});

https://codepen.io/Kidkie/pen/gdaJjZ

Upvotes: 0

Zysce
Zysce

Reputation: 1240

First, add an id to the link and the div (easier to fetch the elements)

<div id="dig-pub" class="dig-pub">
<a id="id" href="/wilson-camo"></a>

Then, get the href

var href = $('#id').attr('href');

Set the value to the div

$('#dig-pub').html(href);

However, you could have find this easily on JQuery documentation.

Upvotes: 0

Sean T
Sean T

Reputation: 2504

You bind a click event to your anchor tag. you'll need to assign a class to the anchor tag too if you have many on the page so replace 'className' with your class name. I'm not sure how you want to assign it to the div so I've done it as a data-attribute as this is the conventional way to go.

$('a.className').on('click', function (){
    $(this).closest('.dig-pub').attr('data-href', $(this).attr('href'));
});

Upvotes: 2

Related Questions