jQuery add class based on parent URL - javascript

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;}

Related

Convert all HTML Links to another URL with HTML and Javascript

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/");

Replace multiple links

I'm trying to replace multiple links but only the first one is replaced,
all the other remain the same.
function rep(){
var text = document.querySelector(".link").querySelector("a").href;
var newText = text.replace(/http:\/\/test(.*)http:\/\/main(.*)com/, 'http://google$2com');
document.querySelector(".link").querySelector("a").href = newText;
}
Any suggestions?
It's multiple a href links inside .link elements which I'm talking about.
Your mistake is in using querySelector, so document.querySelector(".link").querySelector("a") literally translates to: get me the first a inside the first .link;
Use querySelectorAll; and you can combine the two selectors:
Vanilla JS:
[].forEach.call(document.querySelectorAll('.link a'), function(a){
a.href = a.href.replace(/http:\/\/test(.*)http:\/\/main(.*)com/, 'http://google$2com');
});
Or, since you'll select items more often, a little utility:
function $$(selector, ctx){
return Array.from((ctx && typeof ctx === "object" ? ctx: document).querySelectorAll(selector));
}
$$('.link a').forEach(function(a){
a.href = a.href.replace(/http:\/\/test(.*)http:\/\/main(.*)com/, 'http://google$2com');
})
Or in jQuery:
$('.link a').each(function(){
this.href = this.href.replace(/http:\/\/test(.*)http:\/\/main(.*)com/, 'http://google$2com');
});
This doesn't use JQuery, and I've changed your regular expression to something that made more sense for the example. It also works when you run the snippet.
function rep() {
var anchors = document.querySelectorAll(".link a");
for (var j = 0; j < anchors.length; ++j) {
var anchor = anchors[j];
anchor.href = anchor.href.replace(/http:\/\/test(.*)com/, 'http://google$1com');
}
}
rep();
a[href]:after {
content: " (" attr(href)")"
}
<div class="link">
What kind of link is this?
<br/>
And what kind of link is this?
<br/>
</div>
<div class="link">
What kind of link is this?
<br/>
And what kind of link is this?
<br/>
</div>
Edit: Expanded example showing multiple anchor hrefs replaced inside multiple link classed objects.
Edit2: Thomas example is a more advanced example, and is more technically correct in using querySelectorAll(".link a"); it will grab anchors in descendants, not just children. Edited mine to follow suite.
If you intend to only select direct children of link class elements, use ".link>a" instead of ".link a" for the selector.
Try using a foreach loop for every ".link" element. It seems that
every ".link" element have at least 1 anchor inside, maybe just one.
Supposing every .link element has 1 anchor just inside, something like
this should do:
$('.link').each(function(){
// take the A element of the current ".link" element iterated
var anchor = $(this).find('a');
// take the current href attribute of the anchor
var the_anchor_href = anchor.attr('href');
// replace that text and achieve the new href (just copied your part)
var new_href = the_anchor_href.replace(/http:\/\/test(.*)http:\/\/main(.*)com/,'http://google$2com');
// set the new href attribute to the anchor
anchor.attr('href', new_href);
});
I did't test it but it should move you to the way. Consider that we
could resume this in 3 lines.
Cheers
EDIT
I give the last try, looking at your DOM of the updated question and using plain javascript (not tested):
var links = document.getElementsByClassName('link');
var anchors = [];
for (var li in links) {
anchors = li.getElementsByTagName('A');
for(var a in anchors){
a.href = a.href.replace(/http:\/\/test(.*)com/, 'http://google$1com');
}
}
I suggest to read the following post comment for some cooler methods of looping/making stuff foreach item.
How to change the href for a hyperlink using jQuery

How can I make greasemonkey search only within a table

Below is my code and currently it searches the whole webpage. I'm trying to figure out how to make it search only within a table. (There is only one table on the page).
Any help would be appreciated.
var TargetLink = $("a:contains('gg')");
var TargetSink = $("a:contains('u')");
if (TargetLink && TargetLink.length)
{
window.location.href = TargetLink[0].href;
}
else if (TargetSink && TargetSink.length)
{
window.location.href = TargetSink[0].href;
}
var TargetLink = $("table a:contains('gg')");
var TargetSink = $("table a:contains('u')");
EDIT:
You say there is only one table on the page. Do you absolutely know there will only ever be one table? Even if you think the answer is yes, I would try and add an id or class selector so that things won't break in the future.
Also, the following code can be simplified:
if (TargetLink && TargetLink.length)
to:
if (TargetLink.length)
Re: "could I combine those 2 variables into 1":
Use a comma in the selector, like so:
//--- Need more of the HTML structure for a better selector.
var TargetLink = $("table")
.find ("a:contains('gg'), a:contains('u')")
;
if (TargetLink.length) {
window.location.href = TargetLink[0].href;
}
If both kind of links are found, 'gg' will be used (first).

How to get the text after the # symbol in a link?

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);
}

Removing an Element on Certain Location

Let's say the window's location is on htt://stackoverflow.com/index.php, I want to remove an element in the index page with jQuery. This is what I have and it's not working:
$(document).ready(function() {
var location = window.location;
var locQuery = /index/i;
if (location.match(locQuery)) {
$('.someClass').removeClass();
}
});
You are only removing it's class, so for example
<div class="someclass"></div>
will change into
<div></div>.
try
$('.someClass').remove();
I found the problem. window.location is an object so the .match method couldn't match anything from the regex. I had to use the .href property of window.location to get a match.
var location = window.location.href;
var locQuery = /index/i;
if (location.match(locQuery)) {
$('.someClass').remove();
}
I hope I use the right terms. I'm new to JavaScript.

Categories