0

I am trying to dynamically change url under the header with js function. Unfortunately I stack on some easy part.

According to link I tried to solve that problem...

Simplified version of my code:

<div class="details">
  <h1 id="title">Old title</h1>
  <h3 id="author">
    <a id="aId" href="https://www.google.pl/">Old author</a>
  </h3>
</div>

Script:

var title = $("#title");// the id of the heading
var author = $("#author");// id of author 

title.text("New title");
author.text("New author");
var a = document.getElementById('aId');
a.href = "bing.com"

The problem is that Author now is not clickable. Could you help me?

EDIT:

Thanks for your help! Solution:

var title = $("#title");// the id of the heading
var author = $("#author a");// id of author 

title.text("New title");
author.text("New author");
author.attr("href", "http://bing.com")
pb.
  • 321
  • 3
  • 4
  • 21

2 Answers2

2

When you call author.text("New author");, you are removing the link form within the <h3 id="author"> element. It basically goes from:

<h3 id="author">
  <a id="aId" href="https://www.google.pl/">Old author</a>
</h3>

to

<h3 id="author">New author</h3>

You should be changing the name of the author within the link instead of the h3 directly, as follows:

 var title = $("#title");// the id of the heading
 var author = $("#author a");// id of author 

 title.text("New title");
 author.text("New author");
 var a = document.getElementById('aId');
 a.href = "http://bing.com"

Pay special attention that the selector of the author has changed to be the a element within the #author element.

You can test the code here: (wait 3 seconds and you will see the link being updated)

https://jsfiddle.net/nq8hwr2x/

Alex Santos
  • 2,900
  • 1
  • 19
  • 21
  • Thank you for you answer. It is working, but do I really need to two identifiers? like '#author a' and 'aId'? Is there more elegant way? – pb. Oct 15 '17 at 10:33
  • 1
    There's a more elegant way, I just tried to keep changes to a minimum. You can do `author.text("New author").attr("href", "http://bing.com");` and do all the changes in one line. – Alex Santos Oct 15 '17 at 10:34
2

The problem is that you are nesting the <a> tag inside a <h3> tag, which is causing the link to be removed when changing the text attribute. You can just lose the <h3> tag and set the <a> text directly:

$("#title").text("New title");
$("#aId").text("New author").attr("href", "http://bing.com/");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="details">
  <h1 id="title">Old title</h1>
  <a id="aId" href="https://www.google.pl/">Old author</a>
</div>
Koby Douek
  • 16,156
  • 19
  • 74
  • 103