How to change href value using javascript or jquery? - javascript

<div class="container-fluid">
<img class="pull-left" onclick="MarkPopup()" style="width:50px;height:50px" src="/assets/mark.jpg">
<ul class="nav pull-right">
<li>
<li>
Contact Club
</li>
<li>
<li class="dropdown">
</ul>
</div>
I want to change the href value "/ContactClub" to "somethingelse". How is this done please?

Two ways ;)
jQuery style:
// Select a with href attribute = /ContactClub
$('a[href="/ContactClub"]').prop('href', 'newhref...');
Pure-js solution (untested)
var elements = document.getElementsByTagName('a');
for (var i = 0; i < elements.length; i++) {
if (element[i].href === '/ContactClub') {
if (element.setAttribute !== 'function') {
element[i].href = 'newhref';
} else {
element[i].setAttribute('href', 'newhref');
}
}
}

I would add an id to the a tag:
<a id="contact_link" href="/ContactClub">Contact Club</a>
And then do either,
$('#contact_link').attr('href', 'new url');
or,
document.getElementById('contact_link').href = 'new url';
Note: You can also use the jQuery prop method in the same fashion as attr above. This is somewhat a matter of preference. As href is principally thought of as an attribute (with a corresponding, but not dynamic or disconnected js property), I would suggest using attr. Other attributes like value will depend on what you're trying to retrieve. Do a bit of research on the differences.

You can use either prop() or attr():
$('a[href="/ContactClub"]').attr('href', 'New Href here');
or:
$('a[href="/ContactClub"]').prop('href', 'New Href here');
Fiddle Demo

try
$("li a").attr("href","new value");

Related

how can i get an attribute value of all links on a page?

i'm trying to get a list of values of 'data-ctorig' property on all links marked with 'gs-title' class on this page.
i can get one the value of first link
document.querySelector('a.gs-title').getAttribute('data-ctorig')
but can have others.
also, i can get a list of nodelist (idk what is this) using
document.querySelectorAll('a.gs-title')
but i dont know how can i get a list of attribute values based in this node list.
also i've tried use :nth-of-type() but i got only null after first value
var x = document.querySelector("a.gs-title:nth-of-type(1)").getAttribute("data-ctorig")
i'm also using python with selenium webdriver to do this so if someone know how to do it on python 'll help me on the same way.
First use querySelectorAll to get all the .gs-title nodes.
var gstitles = document.querySelectorAll('a.gs-title')
You can use gstitles.length now to determine how many there are.
gstitles.length;
Next we need to setup a for loop.
Check out the code snippet below.
for (i=0;i<gstitles.length;i++)
{
console.log(gstitles[i].getAttribute('data-ctorig'));
}
var gstitles = document.querySelectorAll('a.gs-title')
for (i=0;i<gstitles.length;i++)
{
console.log(gstitles[i].getAttribute('data-ctorig'));
}
<div class="gs-title"><a class="gs-title" href="https://www.teses.usp.br/teses/disponiveis/27/27151/tde-19032008-183924/publico/AmandaTojal.pdf" target="_blank" dir="ltr" data-cturl="https://www.google.com/url?q=https://www.teses.usp.br/teses/disponiveis/27/27151/tde-19032008-183924/publico/AmandaTojal.pdf&sa=U&ved=0ahUKEwiWo7TB3-bhAhUF16wKHaWeCXoQFggEMAA&client=internal-uds-cse&cx=011662445380875560067:cack5lsxley&usg=AOvVaw2g3t_0fFH8wjhfjcku0DL3" data-ctorig="https://www.teses.usp.br/teses/disponiveis/27/27151/tde-19032008-183924/publico/AmandaTojal.pdf"><b>AMANDA</b> PINTO DA FONSECA TOJAL</a></div><div class="gs-title gsc-table-cell-thumbnail gsc-thumbnail-left"><a class="gs-title" href="https://www.teses.usp.br/teses/disponiveis/27/27151/tde-19032008-183924/publico/AmandaTojal.pdf" target="_blank" dir="ltr" data-cturl="https://www.google.com/url?q=https://www.teses.usp.br/teses/disponiveis/27/27151/tde-19032008-183924/publico/AmandaTojal.pdf&sa=U&ved=0ahUKEwiWo7TB3-bhAhUF16wKHaWeCXoQFggEMAA&client=internal-uds-cse&cx=011662445380875560067:cack5lsxley&usg=AOvVaw2g3t_0fFH8wjhfjcku0DL3" data-ctorig="https://www.teses.usp.br/teses/disponiveis/27/27151/tde-19032008-183924/publico/AmandaTojal.pdf"><b>AMANDA</b> PINTO DA FONSECA TOJAL</a></div><div class="gs-title"><a class="gs-title" href="https://www.google.com/url?q=http://www.teses.usp.br/teses/disponiveis/17/17153/tde-06012017-103806/publico/AmandaMizukamiDOCorrig.pdf&sa=U&ved=0ahUKEwiWo7TB3-bhAhUF16wKHaWeCXoQFggGMAE&client=internal-uds-cse&cx=011662445380875560067:cack5lsxley&usg=AOvVaw0Jdjapa8W60DfKRyUIAdoH" target="_blank" dir="ltr" data-cturl="https://www.google.com/url?q=http://www.teses.usp.br/teses/disponiveis/17/17153/tde-06012017-103806/publico/AmandaMizukamiDOCorrig.pdf&sa=U&ved=0ahUKEwiWo7TB3-bhAhUF16wKHaWeCXoQFggGMAE&client=internal-uds-cse&cx=011662445380875560067:cack5lsxley&usg=AOvVaw0Jdjapa8W60DfKRyUIAdoH" data-ctorig="http://www.teses.usp.br/teses/disponiveis/17/17153/tde-06012017-103806/publico/AmandaMizukamiDOCorrig.pdf"><b>AMANDA</b> MIZUKAMI</a></div>
You meant this? :)
var links = document.querySelectorAll('a.gs-title');
var list = [];
links.forEach((link) => {
list.push(link.getAttribute('data-ctorig'));
});
console.log(list);
<a class="gs-title" data-ctorig="Test1"><b>AMANDA</b> MIZUKAMI</a>
<a class="gs-title" data-ctorig="Test2"><b>AMANDA</b> MIZUKAMI</a>
<a class="gs-title" data-ctorig="Test3"><b>AMANDA</b> MIZUKAMI</a>

jQuery elements with attribute greater than passed variable (.filter())

I know I can use jQuery's .filter() for filtering by attribute. I also know that usage of such custom attributes is frowned upon since W3C's official implementation of data-thing in HTML5.
But I still want to know why this is not working.
JS:
$("[id^=hide]").click(function() {
var lvl = $(this).attr('lvl');
var id = $(this).attr('tar');
$('#' + id).slideToggle(100);
$('div').filter(function(lvl) {
return $('this').attr('lvl') > lvl;
}).slideToggle(100);
});
HTML:
<a id="hide1" lvl="0" tar="1"></a>
<div id="1" lvl="0"></div>
<a id="hide2" lvl="1" tar="2"></a>
<div id="2" lvl="1"></div>
<a id="hide3" lvl="2" tar="3"></a>
<div id="3" lvl="2"></div>
<a id="hide4" lvl="2" tar="4"></a>
<div id="4" lvl="2"></div>
<a id="hide5" lvl="1" tar="5"></a>
<div id="5" lvl="1"></div>
<a id="hide7" lvl="2" tar="7"></a>
<div id="7" lvl="2"></div>
What I want to achieve is.
1. Click on the link.
2. SlideToggle the div that is close to the link.
3. SlideToggle all other divs that have level attribute bigger than level attribute of that link.
I was also trying to do it like this:
$("[id^=hide]").click(function() {
var lvl = $(this).attr('lvl');
var id = $(this).attr('tar');
$('#' + id).slideToggle(100);
hideOthers(lvl);
});
var hideOthers = function(lvl) {
$('div').filter(function(lvl) {
return $('this').attr('lvl')> lvl;
}).slideToggle(100);
}
But that's also not working. Any ideas?
Updated Fiddle
In this line on your code :
$('div').filter(function(lvl) {
The lvl considered as index in jquery filter() function, so the value of lvl inside the function is [ 0 - 1 - 2 .... nbr_of_divs ].
to fix that just remove lvl from param and use it directly.
$('div').filter(function() {
return $(this).attr('lvl') > lvl;
}).slideToggle(100);
Removing also apostrophes ( ' ) from $(this) inside filter function :
Replacing :
return $('this').attr('lvl')> lvl;
By :
return $(this).attr('lvl') > lvl;
And it work, Hope that this help.
you can use turnery operator here:
Like
return $('this').attr('lvl')> lvl ? lvl : $('this').attr('lvl');

Javascript, if URL then item

As the title suggests I am looking for a script command for "if url", then "item." I am working on a wordpress theme that I am translating. All of the content has been translated except for 1 item that is essentially a tile menu item.
I figure the best/only way to translate it since the theme does not support multilungual sites is to give it a javascript condition.
Perhaps I am wrong in my approach but I have been trying something like the following:
if(window.location.pathname == "example.com")
{
<li class="b1">
<a href="http://example.com/?page_id=69">
<h5>Example</h5>
<span>Thank you!.</span>
</a>
</li>
}
else
{
<li class="b1">
<a href="http://example.com/?page_id=69">
<h5>Example</h5>
<span>Merci beaucoup!.</span>
</a>
</li>
If anyone could tell me what im doing wrong that would be pretty cool
Thanks
You can't embed HTML into the middle of your javascript like that - everything in a script has to be actual javscript. You can use javascript to insert HTML into the DOM, either at the current position or in other positions in the document. For example, you could do this in your HTML:
<li class="b1">
<a href="http://example.com/?page_id=69">
<h5>Example</h5>
<span><script>
if(window.location.hostname == "example.com") {
document.write("Thank you!.")
} else {
document.write("Merci beaucoup!.")
}
</script></span>
</a>
</li>
You will also have to fix your javascript logic because location.pathname does not contain the domain - perhaps you meant to use .hostname instead.
your if statement is wrong because you are checking your domain against the path.
you should replace
window.location.pathname
with
window.location.hostname
put the javascript only where you need the text replaced: no need to write all the html twice.
if(window.location.hostname == "example.com") {
document.write("Thank you!.")
} else {
document.write("Merci beaucoup!.")
}
Something like this works.
<ul>
<li class="b1"> </li>
</ul>
<script language="javascript">
if(window.location.hostname == "example.com") {
document.querySelector('.b1').innerHTML = "<a href='http://example.com/?page_id=69'><h5>Example</h5><span>Thank you!.</span></a>";
}
else
{
document.querySelector('.b1').innerHTML = "<a href='http://example.com/?page_id=69'><h5>Example</h5><span>Merci beaucoup!.</span></a>";
}
You maybe should use a regular expression to catch the url, did you already tried?
<li class="b1">
<a href="http://example.com/?page_id=69">
<h5>Example</h5>
<span><script>
var expression = /[-a-zA-Z0-9#:%_\+.~#?&//=]{2,256}\.[a-z]{2,4}\b(\/[-a-zA-Z0-9#:%_\+.~#?&//=]*)?/gi;
var regex = new RegExp(expression);
if (window.location.hostname.match(regex) ){
<span>Thank you!.</span>
}
else{
<span>Merci beaucoup!.</span>
}
</script></span>
</a>
</li>

Get the ID of a sibling after a link is clicked

I use the following code and I would like to be able to get the ID attribute from the <li> (the post ID) that is associated with an <a> when it is clicked, but I cannot figure out how do do this. Is anybody able to help me at all?
<li id="custom_latest_news-5" class="widget custom_widget_latest_news">
<div class="widget-title">
Latest news
</div>
<div class="widget-content">
<ul class="link-list ajax-links">
<li id="post-5521">Last call for self-assessment tax forms</li>
<li id="post-5523">Young drivers gambling on no insurance</li>
<li id="post-5520">Tenants forced to abandon pets</li>
</ul>
</div>
</li>
Here is the JS that I currently have -
/**
* Intercept a click for page refresh and run the page refresh JS
*/
$(function(){
$('.ajax-links').delegate('li a', 'click', function(e){
/** Prevent the click from doing anything */
e.preventDefault();
/** Get the post ID */
var post_id = '???';
});
});
Thanks.
I believe you need
var post_id = $(this).parent().attr('id');
Example: http://jsfiddle.net/FwqGT/
You could use:
var post_id = $(this).parent().attr("id");
If you need to get the following (sibling) <li>, you could also do:
var next_id = $(this).parent().next().attr("id");
The li:s with the post ids in your markup are actually not siblings but parents.
This ought to do it:
var post_id = $(this).parent().attr('id'));

jquery / javascript insert ul / li elements into this html

is it possible to amend the following html into the source linked at the bottom of this page? I have limited scripting access to the source page so I'm looking for a way to change the page using jquery or js.
Also the department id's will be completely random and there will be a different number of links relative to each group, therefore it will need to be dynamic. I've tried appending but I'm having trouble as inserting starting or closing tags only, so not sure how to go about this. Thanks in advance for any help offered.
Additions I need in the code are marked with **'s
Original source:
<ul class="menu">
<a id="group-car" href="#">Car</a>
<li><a id="department-2" href="link">Black</a></li>
<li><a id="department-4" href="link">Blue</a></li>
<a id="group-bike" href="#">Bike</a>
<li><a id="department-1" href="link">BMX</a></li>
<li><a id="department-6" href="link">Racing</a></li>
<li><a id="department-12" href="link">Mountain</a></li>
</ul>
What I need to end up with:
<ul class="menu">
**<li>**
<a id="group-car" href="#">CAR</a>
**<ul class="acitem">**
<li><a id="department-2" href="link">Black</a></li>
<li><a id="department-4" href="link">Blue</a></li>
**</ul>**
**</li>**
**<li>**
<a id="group-bike" href="#">BIKE</a>
**<ul class="acitem">**
<li><a id="department-1" href="link">BMX</a></li>
<li><a id="department-6" href="link">Racing</a></li>
<li><a id="department-12" href="link">Mountain</a></li>
**</ul>**
**</li>**
</ul>
jQuery(".menu").children("a").each(function()
{
jQuery(this).nextUntil("a").add(this).wrapAll("<li></li>");
jQuery(this).nextUntil("a").wrapAll("<ul></ul>");
});
jsfiddle
Does this need some explanation?
EDIT oops! I didn't see the classes on them:
jQuery(".menu").children("a").each(function()
{
jQuery(this).nextUntil("a").add(this).wrapAll("<li></li>");
var jUL = jQuery("<ul></ul>").addClass("acitem");
jQuery(this).nextUntil("a").wrapAll(jUL);
});
jsFiddle
What a beautiful challenge!!
Here you have. Tested in FF 3.6 and works!
function fixMarkup(){
var liFamilies = [];
var iFamily = 0;
$(".menu li").each(function(){
if($(this).prev().is("a"))
liFamilies[iFamily] = [this]; //Start a family
else
liFamilies[iFamily].push(this); //Append to family
if($(this).next().is("a")) iFamily++; //A new family begins
});
//console.log(liFamilies);
for(var i = 0; i< liFamilies.length; i++){
var family = liFamilies[i];
$(family).wrapAll('<ul class="acitem" />');
var ulNew = $(family[0]).parent()[0];
var aElem = $(ulNew).prev()[0];
$([aElem, ulNew]).wrapAll("<li/>");
}
}
$(document).ready(function(){
fixMarkup();
});

Categories

Resources