Reputation: 341
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")
Upvotes: 0
Views: 2035
Reputation: 16675
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>
Upvotes: 2
Reputation: 2950
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/
Upvotes: 2