How can I use javascript to convert relative href attributes to absolute paths?

I have a template that receives a screenshot from an external provider and should include absolute paths in navigation, so the content hosted on an external server will correctly link to our site.

Currently, the page / template is controlled by a global menu application written by our back end development team ... therefore, everyone who updates our site enters and changes the menu and their paths ...

Currently, all links are tied to relative paths to the root.

for example

<a href="/">Home</a>
<a href="/news/">News</a>
<a href="/media/">Media</a>
<a href="/other/">Other</a>

I need a simple way (preferably with jquery) to add http://www.domain.com "to each of these links.

+3
6
$('a').attr('href', 'http://www.domain.com'+$(this).attr('href'));
+3

, jQuery $( "a" ). attr ( "href" ) $( "a" ). get (0).href?

$("a").each(function() {
   alert(this.href);
   $(this).attr("href") = this.href;
});

, , javascript . , , .

+2

javascript . . , jquery-, . , , :

$('a.external').each(function() {
    $(this).attr('href', domain_name + $(this).attr('href'));
})
+1

jquery ....

var elements = document.getElementsByTagName("a");
var eachLink;
for (eachLink in elements) {
 var relativeLink = eachLink.href;
 var absoluetLink = ["http://",domainName,"relativeLink"];
 eachLink.href = absoluteLink.join("");
}

- , , jquery 6 : P

+1

:

$('a').each(function(){$(this).attr('href',this.href);});

href HTMLAnchorElement, , attr() JQuery.

+1

, href, "/". - , js-uri. , , , .

0

Source: https://habr.com/ru/post/1707806/


All Articles