Replace href value by getting current URL - javascript

I have a menu in Wordpress that uses WP Menu system. All links are basically custom links that output the following (WP classes removed for brevity):
<ul>
<li>About
<ul>
<li>Section 1</li>
<li>Section 2</li>
<li>Section 3</li>
</ul>
</li>
<li>Services
<ul>
<li>Section 1</li>
<li>Section 2</li>
<li>Section 3</li>
<li>Section 4</li>
</ul>
</li>
</ul>
I'm trying to remove the domain part of the URL if the parent page is being viewed so if I were viewing the About page the links in the menu would change to:
<li>About
<ul>
<li>Section 1</li>
<li>Section 2</li>
<li>Section 3</li>
</ul>
</li>
<li>Services
<ul>
<li>Section 1</li>
<li>Section 2</li>
<li>Section 3</li>
<li>Section 4</li>
</ul>
</li>
</ul>
The problem I have with jQuery is that I cannot target each specific page because the pages will be unknown, I therefore need it to get the URL and match it with the correct part of the menu to change the links. I have tried this but its too specific:
if (window.location.href.indexOf("about") != -1) {
//do something
} else {
//do something else
}
EDIT
I only want to alter the links in the menu for the current page. The answers so far change all of the link in the menu, I just want to target the links found on the same page.

DEMO here
Firstly add a class sections to the ul element to make it easy to target.
<ul class="sections">
<li>Section 1
</li>
<li>Section 2
</li>
<li>Section 3
</li>
</ul>
Use .map() to replace the href for each anchor.
EDIT - based on your new update & I liked #Archer's update too. This should work.
$(".sections a[href* = '" + window.location.pathname + "/#']").map(function(){
var currentsection = this.href.split('/').pop();
this.href = currentsection;
});

Another option...
$(function() {
$("a[href*='" + window.location.pathname + "#']").attr("href", function() {
return "#" + this.href.split("#")[1];
});
});
This will find all the links with the current page and a # in them and fix the href value accordingly.

Try this,
$('a').each(function(){
// check the anchor tab href has location.href or not
if($(this).attr('href').indexOf(window.location.href) != -1)
{
// some code to replace location.href to blank
var href=$(this).attr('href').replace(window.location.href,'');
$(this).attr('href',href);
}
});
Alternatively, try this,
$('a').each(function(){
if(this.href.indexOf('#') != -1)
{
var href=this.href.split('#')[1];
this.href = '#'+href;
}
});

Related

How to add link in tabs in Bootstrap?

I want to create a link in a Bootstrap tab. I have 3 tabs and I want one of them where I will click and a new page will be opened. Please let me know how I can do it.
Here is my HTML code.
<li><a data-toggle="tab" href="google.com" id="btnRent" style="background: #f4762a;">Rent/Lease/PG/Shop</a></li>
And I am using this jQuery...
<script type="text/javascript">
$(document).ready(function()
{
$(#btnRent).click(function()
{
var go_to_url = "www.google.com";
document.location.href = go_to_url;
});
});
</script>
But it's not working. I want to open a new page when someone clicks on the "Rent/Lease/PG/Shop" tab.
you can try inside your click function:
window.location = url;
or window.open(url);
it should do the trick..
you don't need javascript for that, just use the target parameter inside your 'a' tag like this:
<li><a data-toggle="tab" href="https://google.com" target="_blank" id="btnRent" style="background: #f4762a;">Rent/Lease/PG/Shop</a></li>
The best way to do this is to create another "" element inside your tab ""
<ul class="nav nav-tabs">
<li class="active">Home<a href="http://www.google.com>Click here</a></li>
<li>Menu 1</li>
<li>Menu 2</li>
<li>Menu 3</li>
</ul>
If you want a direct click just do this
<ul class="nav nav-tabs">
<li><a href="http://www.google.com>Click here</a></li>
<li>Menu 1</li>
<li>Menu 2</li>
<li>Menu 3</li>
</ul>

Get Word from href using jQuery

Heyo,
so I got a script that turns normal anchor href's into id hrefs (for example: /10001-Link1 to #Link1). Now this works fine as long as you repeat the code for every single anchor link you want to turn into a id link. But I want to make it less static. So that instead of repeating the code for every single anchor link the script should get the correct word out of the current anchor href automaticly and just replaces the word with the rest of the url and puts a # before it.
So here is the code that works only for the first URL:
$(document).ready(function() {
$('li a').each(function(){
var oldUrl = $(this).attr("href");
var newUrl = oldUrl.replace("/10001-Link1", "#Link1");
$(this).attr("href", newUrl);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul>
<li>Link 1</li>
<li>Link 2</li>
<li>Link 3</li>
<li>Link 4</li>
<li>Link 5</li>
</ul>
Now I alredy searched for a solution for this Problem. But the only thing I found was a line of code I couldn't really understand.
$('a[href^="http://stackoverflow.com"]')
.each(function()
{
this.href = this.href.replace(/^http:\/\/beta\.stackoverflow\.com/,
'http://stackoverflow.com');
});
I get the first part were every href that starts with http://stackoverflow.com is getting a .each function. But I don't know what all the /'s and \'s by the .replace part do and mean. Maybe this is not even the right solution for my problem at all?
You can use a regex for that.
.replace(/\/[0-9]{5}-/, ""); replaces the regex match with an empty string. Just add a # in front of it and you got the desired result.
The regex works as followed:
\/ looks for a / (need to be escaped).
[0-9]{5} looks for 5 numbers.
- looks for (you never believe it) a -.
$(document).ready(function() {
$('li a').each(function(){
var oldUrl = $(this).attr("href");
var newUrl = "#" + oldUrl.replace(/\/[0-9]{5}-/, "");
$(this).attr("href", newUrl);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul>
<li>Link 1</li>
<li>Link 2</li>
<li>Link 3</li>
<li>Link 4</li>
<li>Link 5</li>
</ul>
You can use lookbehind assertion (which should have a decent support):
var newUrl = oldUrl.match(/((?<=-)).*$/)[0]
this will retrieve anything after the -,
then you can use the variable to compose the new href.
$(document).ready(function() {
$('li a').each(function(){
var oldUrl = $(this).attr("href");
var newUrl = '#' + oldUrl.match(/((?<=-)).*$/)[0]
$(this).attr("href", newUrl);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul>
<li>Link 1</li>
<li>Link 2</li>
<li>Link 3</li>
<li>Link 4</li>
<li>Link 5</li>
</ul>
you can do something like this:
$(document).ready(function () {
$('li a').each(function () {
var url = this.href;
url = url.split('-')[1];
this.href = this.href.replace(this.href, "#" + url);
});
});
You can do it using the regular expression /\/\d{0,5}-(.*)$/ that means: from the /, 5-digit digits and - to the end of the string..
Code:
$('li a').each(function () {
this.href = '#' + this.href.match(/\/\d{0,5}-(.*)$/).pop();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul>
<li>Link 1</li>
<li>Link 2</li>
<li>Link 3</li>
<li>Link 4</li>
<li>Link 5</li>
</ul>

Trying to parse tag element

I am trying to parse a web page with JavaScript targeting list <li> without class.
<ul id="cartItems">
<li class="heading">
<li>...</li>
<li>...</li>
<li>...</li>
<li>...</li>
</ul>
Use querySelectorAll to get all li elements without a class.
var liWithoutClass = document.querySelectorAll('#cartItems > li:not([class])');
console.log(liWithoutClass);
document.write(liWithoutClass[0].textContent); // Output the first li
document.write('<br />' + liWithoutClass[3].textContent); // Output the last li
<ul id="cartItems">
<li class="heading">Heading</li>
<li>Element 1</li>
<li>Element 2</li>
<li>Element 3</li>
<li>Element 4</li>
</ul>
var elems = document.querySelector(".heading");
console.log(elems);
//Now we strip the class out like this:
elems.setAttribute(class, "none");
//Now we display the updated values below
console.log(elems);
// This won't work in Stack's editor, so you'll have to validate it against the page you want.
//Now, just grab the entire element by id from the page as below:
var updatedContent = document.getElementById("cartItems");
console.log(updatedContent);
//Again, stack's editor is limited, but overall this should work fine on your page.
<ul id="cartItems">
<li class="heading">
<li>item 1</li>
<li>item 2</li>
<li>item 3</li>
<li>item 4</li>
</ul>

Jquery, get values from <li> tag

I have list with id myid. I can get values li values like this $('#' + i).text(). But I am using $( '#myid' ).sortable() . How can get values in currently displayed order? Demo here. I need to implement function in stop:
<ul id='myid'>
<li id='1'>value 1</li>
<li id='2'>value 2</li>
<li id='3'>value 3</li>
<li id='4'>value 4</li>
<li id='5'>value 5</li>
</ul>
Use .each() with .text() : Updated Fiddle
stop:function(){
$('li',this).each(function(){
alert($(this).text())
});
}
or map() to get them into array.
stop:function(){
var $li= $('li',this).map(function(){
return $(this).text()
});
alert($li)
}

JQuery remove li based on ascii contents

I'm dynamically adding list items to a ul
<ul>
<li>thing 1</li>
<li>thing 2</li>
<li class='colorblock'>thing 3</li>
<li class='colorblock'>thing 4</li>
<li>thing 5</li>
</ul>
In some situations I need to enclose a few of the li with the following
$('.colorblock:first').before('<li>[± </li>');
$('.colorblock:last').append('<li>]</li>');
that products the following
<ul>
<li>thing 1</li>
<li>thing 2</li>
<li>[± </li>
<li class='colorblock'>thing 3</li>
<li class='colorblock'>thing 4</li>
<li>]</li>
<li>thing 5</li>
</ul>
now, if I also may need to remove those two li's with something along the following
$('li').filter(function() { return $.text([this]) === '[± '; }).remove();
$('li').filter(function() { return $.text([this]) === '[± '; }).remove();
$('li').filter(function() { return $.text([this]) === ']'; }).remove();
my problem is that none of these are correctly matching to
<li>[± </li>
I've ran out of ideas on how to strictly match and remove that li. any suggestions?
Try
$('li').filter(function(){
var txt = $.trim($(this).text());
return txt == '[±' || txt == ']'
}).remove()
Demo: Fiddle
Turns out it was an encoding issue with the file it was in, needed to be UTF-8

Categories