0

I am trying to change html href attribute value ?post=55 to ?post=44 with button click using jQuery, but don't know how.

HTML

<button class="button">button</button>

<a href="posts.php?post=55" class="post-link">Post</a>

JAVASCRIPT

$('.button').on('click', function() {

  
});

This is what I have

<a href="posts.php?post=55" class="post-link">Post</a>  

This is what I want when clicking button

<a href="posts.php?post=44" class="post-link">Post</a> 
Pleinair
  • 437
  • 9
  • 21

2 Answers2

2

A Jquery function allows you to change an attribute of a tag. It is written as $("tag").attr('attr','newvalue'). In your case, you can do $("a").attr('href','posts.php?post=44') inside the click function (you should probably give the a tag an id too)

ry kim
  • 93
  • 9
  • jQuery provided 'attr()' function to modify HTML attributes, ` $(document).ready(function(){ $(".button").click(function(){ $("#Id_Of_Your_Button").attr("href", "newURL"); }); });` – Mohit Jul 10 '22 at 18:11
0

"on-click" handler has $(this) that you can use to navigate in the DOM tree if you know that the object you want to alter is relatively placed (from what I see you have <a/> following <button/>.

$('.button').on('click', function() {
    $(this).parent().find('.post-link').attr('href', '#hello-world')
})

JSFiddle

If you want to change a link of the element that is somewhere on the page, I would suggest searching by id value (the id should be unique). Let's say you have <a id="my-id" href="...">...</a>, then:

$('.button').on('click', function() {
    $('#my-id').attr('href', '#hello-world')
})
Victor Perov
  • 1,697
  • 18
  • 37