Reputation:
In a webpage (from remote server where I have no access) I want to insert the page URL after a certain element, and after the webpage loads.
My solution is posted in the snippet below
var address = document.URL;
var pane = document.getElementsByClassName("heading--large")[0];
pane.after("<a href=\"" + address + "\">" + address + "</a>");
The page's URL is inserted, but only as text, not as a recognized element.
The URL is NOT active like the other links. Take a look at the snapshot I uploaded.
Why is the text in my anchor-element not rendering blue? Furthermore the "href" is not highlighted red like the other anchor elements are below.
Is ".after()" not the suitable function?
Upvotes: 3
Views: 78
Reputation: 43880
.after()
places nodes after a given element. A node is many things, but there's two types of nodes we usually are concerned with are elements and text. Your requirements are:
Create an <a>
Add href
attribute with a pre-determined value to <a>
*
Add pre-determined text content to <a>
*
Place <a>
after .heading--large
*
*#2, #3, and #4 can be in any order
.after()
can only do #4, so here's a possibility if you really want to use .after()
:
const A = document.createElement('a')
A.href = address
A.textContent = address
pane.after(A)
const address = document.URL;
// This a modern equivalent
const pane = document.querySelector(".heading--large");
/*
This will safely render htmlString at a specfic location in relation to a given element.
*/
pane.insertAdjacentHTML("afterEnd", `<a href="${address}">${address}</a>`);
// Check to see if it's correct with .outerHTML property
console.log(document.querySelector("header").outerHTML);
<header>
<h1 class='heading--large'>Chrome Extensions</h1>
</header>
Upvotes: 0
Reputation: 2279
In your code, you are inserting a string after the pane
node as the Element.after
documentation shows. If you want to use after
, modify your code with document.createElement
and modify the resulting elements to mirror your original intent
var address =
"https://www.ghacks.net/2021/10/02/which-are-the-best-screenshot-extensions-for-chrome/";
var pane = document.getElementsByClassName("heading--large")[0];
var myLink = document.createElement("a");
myLink.href = address;
myLink.textContent = address;
pane.after(myLink);
<main class="post-list mt--60 mt--first--0">
<h1 class="heading--large" style="color:#43414e;font-weight:400;"> Which are the best screenshot extensions for Chrome? </h1>
<div class="text-small ghacks-links ghacks-links--smallunderline mt--10 mb--20" style="font-size: 14px;opacity:0.9;margin-top:10px;margin-bottom:20px;"> by Shaun on October 02, 2021 in Google Chrome extensions - Last Update: September 30, 2021 - 6 comments </div>
</main>
Upvotes: 2