Hii i am trying to change the anchor tag href with class media-url with the nearest anchor tage url which is inside field__item div , but i am getting undefined , please let me know where i am doing wrong .
<div > <a href="https://examplelist/item.com" target="_blank" rel="noopener nofollow noreferrer">
</a>
</div>
<div >
<header >
<h2 >Group Exercise Programs</h2>
<h4 ></h4>
</header>
<div >
<div >
<div >media image url</div>
<div ><a href="https://www.example.com/" target="_blank" rel="noopener nofollow noreferrer">https://www.example.com/</a></div>
</div>
</div>
</div>
here is my jquery :
let mediaimageurl = $('.media-url').find('.field__item a').attr('href');
$('.media-url').attr('href' , mediaimageurl);
CodePudding user response:
You need to use closest() to get the parent container and then next() to get .component-spotlight__inner and finally use find() to get the container of your link.
let mediaimageurl = $('.media-url').closest('.media--bundle--image').next('.component-spotlight__inner').find('.field__item a').attr('href');
$('.media-url').attr('href' , mediaimageurl);
console.log(mediaimageurl);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div > <a href="https://examplelist/item.com" target="_blank" rel="noopener nofollow noreferrer">
</a>
</div>
<div >
<header >
<h2 >Group Exercise Programs</h2>
<h4 ></h4>
</header>
<div >
<div >
<div >media image url</div>
<div ><a href="https://www.example.com/" target="_blank" rel="noopener nofollow noreferrer">https://www.example.com/</a></div>
</div>
</div>
</div>