I am trying get all HTML links in a website's body section within a string and replace them to another link.
Tried something like this but did not work:
var search = "https://www.cloudflare.com/5xx-error-landing?utm_source=error_footer";
var replacement = "https://example.com/";
document.body.innerHTML = document.body.innerHTML.split(search).join(replacement)
Where "https://www.cloudflare.com/5xx-error-landing?utm_source=error_footer" is the link I want to replace and "https://example.com/" is the link that I want to replace with.
How about this:
$("[href='your link']").attr("href","new link");
Here is a solution with plain javascript as per your question
document.querySelectorAll("[href='" + search + "']").forEach(function(el){
el.href = replacement );
});
If you want to use jQuery, as you tagged, follow the answer of Nir Tzezana
$('body').find('a').each(function(){
$(this).attr('href','your_new_link');
});
or for different href:
$('body').find('a').each(function(){
var ahref = $(this).attr('href');
if ( ahref == 'your_old_link') { /// or ahref.indexOf("your_old_link") >= 0
$(this).attr('href','your_new_link_1');
}else{
$(this).attr('href','your_new_link_2');
}
});
Just use
$("body a[href='https://www.cloudflare.com']").attr("href","https://example.com/");
Related
on my homepage, I currently have a jQuery that adds a class (in this case an underline) to the link element. This works great and is based on comparing the url (url/firstsubmenu) in the browser with the href of the link element.
However as soon as I go to a child of that link element (url/firstsubmenu/secondsubmenu), the class is gone. I have tried to split the url so that the jQuery always looks for the parent but I just can't solve it. Can you help me?
Could it be solved by adding another code, like maybe "if (this).children().length > 0 ?"
Here is my jQuery:
var cururl = window.location.href;
cururl = cururl.split('#')[0];
jQuery("a.rs-layer").each(function(){
if(jQuery(this).attr('href')=== cururl){
jQuery(this).addClass("current-slider-menu");
}
});
EDIT: I am new to this, and I have tried so many different codes, googled for hours. I now know that I can only write JavaScript in my CMS. That is, I cannot use jQuery operators such as, for example, $.
Try this,
Change the class/selectors as per your requirement. This will add a unique class in the li element, now you can style this using css.
$(document).ready(function() {
$(".main_menu li").removeClass('current-slider-menu');
$(".main_menu li>a").filter(function(){
return this.href == location.href.replace(/#.*/, "");
}).parent("li").addClass("current-slider-menu");
});
You're definitely on the right track.
You can grab the currentURL (before the anchor #):
const currentURL = window.location.href.split('#')[0];
Then you can split the currentURL into its constituent folders:
const currentURLArray = currentURL.split('/');
Then, separately, you can grab all the myLinks:
const myLinks = [...document.querySelectorAll('a.rs-layer')];
And finally you can cycle through myLinks and if the name of the folder you want to match does match the name of the equivalent folder in the currentURL, then you can add the .current-slider-menu class:
for (myLink of myLinks) {
if (myLink.href.split('/')[1] === currentURLArray[1]) {
myLink.classList.add('current-slider-menu');
}
}
Complete Example:
const currentURL = window.location.href.split('#')[0];
const currentURLArray = currentURL.split('/');
const myLinks = [...document.querySelectorAll('a.rs-layer')];
for (myLink of myLinks) {
if (myLink.href.split('/')[1] === currentURLArray[1]) {
myLink.classList.add('current-slider-menu');
}
}
EDITED
try this
var cururl = window.location.href;
jQuery("rs-layer[id|='"+cururl.split('/')[3]+"'] , .rs-layer[href='"+cururl+"']").each(function(){
jQuery(this).addClass("current-slider-menu");
});
I solved it like this instead, skipping the whole idea with text-decoration.
I added an arrow. Finished.
JS:
var url = window.location.href;
var msg = document.getElementById('current-menu-item-arrow');
if( url.search( 'my-word' ) > 0 ) {
msg.style.display = "block";
}
CSS:
#current-menu-item-arrow {display:none;}
I have a simple link with a hashtag in it. ie:
<a class="page_navigation" href="#something">click</a>
On clicking this, I would like to just end up with the 'something' part (minus the hash) in a var.
So far I have
$('.page_navigation').click(function(e)
{
e.preventDefault();
var href = $(this).attr('href');
});
Obviously I just end up with '#something' in my href var with the above code, and I understand I could do some kind of regex (not sure how yet) to strip the #, but I wonder if there is an easier way to access this part of the href I'm unaware of, without having to go through some find and replace code.
Any ideas?
Note: I also know I could store the 'something' in a data tag, but I'm trying to keep this code as DRY as possible.
If you know it has a # in it, you can use this:
$('.page_navigation').click(function(e)
{
e.preventDefault();
var hash = this.href.replace(/^.*#/, "");
});
If you don't know whether it has one it it or not, you can use this:
$('.page_navigation').click(function(e)
{
e.preventDefault();
var hash = "";
if (this.href.indexOf("#") {
hash = this.href.replace(/^.*#/, "");
}
});
In HTML5, you could use:
this.hash
but that is only for the latest browsers.
var theHash = $(this).prop("hash").substr(1);
Related answer to another question
Demo http://jsfiddle.net/UR3XN/
code
$('.page_navigation').click(function(e)
{
e.preventDefault();
var href = $(this).attr('href');
var equalPosition = href.indexOf('#'); //Get the position of '#'
var withouthash = href.substring(equalPosition + 1);
alert(withouthash);
});
You don't need regular expressions for this. You can simply do
var fragment;
if (window.location.hash) {
fragment = window.location.hash;
}
Note that this will pick up the # symbol as well. So,
fragment = "#something"
If you don't want the # symbol, use substring like this:
fragment = window.location.hash.substring(1)
If you want to pick out the hash fragment from an anchor tag, you can do this:
var link = $('#yourAnchor').attr('href');
var fragment;
if (link.indexOf("#") !== -1) {
fragment = link.substr(link.indexOf("#") + 1);
}
My sixth line of code does not work. Please help.
function ajax() {
$('a[class="ajax-cw"]').click( function() {
$('#cw').load( this + "?ajax" );
$('#nav li.current').removeClass('current');
var $base = $("base").attr("href"),
$link = this.replace($base, ""); //Line does not work
alert ($link);
return false;
});
};
if you were trying to replace parts of the href contents of the currently clicked link with that of the base object, you have to access the href contents via
var currenthref = $(this).attr('href');
and then use currenthref in the replace line.
$link = currenthref.replace($base, "");
Thre replace function on this will not properly work because it is not a string but rather an object (most likly jquery) that represents the link element you klicked on.
try this:
this.href.replace($base, '');
this in line 6 is the <a /> tag, not the href of that tag. $(this).attr('href').replace($base,"") will perform better.
You need to end the previous line with a semi-colon. You have ended it with a comma.
var $base = $("base").attr("href");
Using javascript I'm looping through my H3 elements like this:
$('h3').each(function(){ });
I'm then generating an anchor for that tag formatted like this: "section-x" where x increments for each H3 on the page. The problem I have is that I'd like the first letter of the header to be an anchor link, like this:
*H*eading
.. where H is underlined, representing a link. I can format the anchors however I don't know how to wrap a hyperlink tag around the first letter in each heading. Some help would be greatly appreciated.
Regards,
kvanberendonck
Something like this?
$('h3').each(function(){
var currentHeading = $(this).text();
$(this).html("<a href='link'>" + currentHeading.substr(0,1) + "</a>" + currentHeading.substr(1, currentHeading.length - 1));
});
Let's throw some plain javascript into the mix:
$('h3').html(function(i){
var self = $(this)
, html = self.html()
return html[0].anchor('section-'+i) + html.substring(1)
})
html (and most other setter functions) accepts a function as an argument and uses the return value for each element
"string".link(target) creates the code string. A nice vintage useful method
edit: switched from .link to .anchor. Anchors are deprecated though, you should start using IDs for that:
$('h3').html(function(i){
var self = $(this)
, text = self.text()
// give the H3 an id and link to it
// ideally the headers should already have an id
this.id = 'section-'+i
return text[0].link('#section-'+i) + text.substring(1)
})
$('h3').each(function(i){
var firstLetter = $(this).text()[0];
$(this).html('' + firstLetter + '' + $(this).text().substr(1));
});
Not sure where you'd like to put section-x in that heading, but you can use i inside that each() to get the current iteration index.
How can I wrap every element belonging to a particular class with a link that is built from the text inside the div? What I mean is that I would like to turn:
<foo class="my-class>sometext</foo>
into
<a href="path/sometext" ><foo class="my-class>sometext</foo></a>
Url encoding characters would also be nice, but can be ignored for now if necessary.
EDIT: Just to clarify, the path depends on the text within the element
Use jQuery.wrap() for the simple case:
$(".my-class").wrap("<a href='path/sometext'></a>");
To process text inside:
$(".my-class").each(function() {
var txt = $(this).text();
var link = $("<a></a>").attr("href", "path/" + txt);
$(this).wrap(link[0]);
});
$(".my-class").each(function(){
var thisText = $(this).text();
$(this).wrap("<a></a>").attr("href","path/"+thisText);
});
you can wrap them inside anchor element like this:
$(document).ready(function(){
$(".my-class").each(function(){
var hr="path/"+$(this).text();
$(this).wrap("<a href='"+hr+"'></a>");
});
});
if you are opening links in same page itself then easier way than modifying dom to wrap elements inside anchor is to define css for the elements so that they look like links then handle click event:
$(".my-class").click(function(){
window.location.href="path/"+$(this).text();
});
$("foo.my-class").each(function(){
var foo = $(this);
foo.wrap("<a href='path/" + foo.Text() +"'>");
});
This ought to do it:
$('foo.my-class').each(function() {
var element = $(this);
var text = element.html(); // or .text() or .val()
element.wrap('');
});