Setting href attribute at runtime
To get or set an attribute of an HTML element, you can use the element.attr()
function in jQuery.
To get the href attribute, use the following code:
var a_href = $('selector').attr('href');
To set the href attribute, use the following code:
$('selector').attr('href','http://example.com');
In both cases, please use the appropriate selector. If you have set the class for the anchor element, use '.class-name'
and if you have set the id for the anchor element, use '#element-id'
.
Replace href value at runtime
You have to iterate over all the controls in the ControlsCollection
and update the Href
property of all controls that are of type HtmlAnchor
, like this:
private void UpdateTags(Control page)
{
foreach (Control ctrl in page.Controls)
{
if (ctrl is HtmlAnchor)
{
((HtmlAnchor)ctrl).HRef = "myNewlink";
}
else
{
if (ctrl.Controls.Count > 0)
{
UpdateTags(ctrl);
}
}
}
}
How to change the href attribute for a hyperlink using jQuery
Using
$("a").attr("href", "http://www.google.com/")
will modify the href of all hyperlinks to point to Google. You probably want a somewhat more refined selector though. For instance, if you have a mix of link source (hyperlink) and link target (a.k.a. "anchor") anchor tags:
<a name="MyLinks"></a>
<a href="http://www.codeproject.com/">The CodeProject</a>
...Then you probably don't want to accidentally add href
attributes to them. For safety then, we can specify that our selector will only match <a>
tags with an existing href
attribute:
$("a[href]") //...
Of course, you'll probably have something more interesting in mind. If you want to match an anchor with a specific existing href
, you might use something like this:
$("a[href='http://www.google.com/']").attr('href', 'http://www.live.com/')
This will find links where the href
exactly matches the string http://www.google.com/
. A more involved task might be matching, then updating only part of the href
:
$("a[href^='http://stackoverflow.com']")
.each(function()
{
this.href = this.href.replace(/^http:\/\/beta\.stackoverflow\.com/,
"http://stackoverflow.com");
});
The first part selects only links where the href starts with http://stackoverflow.com
. Then, a function is defined that uses a simple regular expression to replace this part of the URL with a new one. Note the flexibility this gives you - any sort of modification to the link could be done here.
How can I add href attribute to a link dynamically using JavaScript?
var a = document.getElementById('yourlinkId'); //or grab it by tagname etc
a.href = "somelink url"
Setting an active class and href attribute for link based on the current page's metadata
Here's what I came up with. I first made a reference the meta tag and got its information, then looped over your links and added the class if necessary. Also note that I added a data-page
attribute to your links to make for a better match of data. I considered slicing the href but realized that could insert problems later on. If the meta tag will always match the what you have inside the anchor, you could also compare the page title to the links[i].innerHTML
and that will work just as well.
let metas = document.getElementsByTagName('meta');
// Find the tag and get its contentlet pageTitle;
for(let i = 0; i < metas.length; i++) { if(metas[i].getAttribute("name") === "application-name") { pageTitle = metas[i].getAttribute("content"); }}
// Find the nav a and give it the linklet container = document.getElementById("navbarSupportedContent");let links = container.getElementsByClassName("nav-link");
for(let i = 0; i < links.length; i++) { if(links[i].getAttribute("data-page").toLowerCase() === pageTitle.toLowerCase()) { links[i].className += " active"; links[i].href = "#"; }}
<head><link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet" /><script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script><script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
<meta name="application-name" content="Home"> </head>
<nav class="navbar navbar-expand-lg navbar-light bg-light fixed-top">
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav mr-auto"> <li class="nav-item"> <a class="nav-link" href="/home" data-page="home">Home</a> </li> <li class="nav-item"> <a class="nav-link" href="/about" data-page="about">About</a> </li> <li class="nav-item"> <a class="nav-link" href="/contact" data-page="contact">Contact</a> </li> </ul> </div></nav>
dynamically passing href in anchor tag
Update your JavaScript function like this:
function check_role()
{
var r=document.getElementById('role').value;
alert(r);
location.href = r;
}
Accessing href attribute using invoke() in each() Cypress
I don't think .get()
is appropriate - it only works from the <body>
not from each '.bms-scoreboard__game-tile--mls'
.
Try .find()
instead
With jQuery operators
cy.get('.bms-scoreboard__game-tile--mls')
.each(($el,index,$list) => {
const href = $el.find('a').attr('href')
cy.request(href)
.its('status')
.should('eq', 200)
})
})
or with Cypress operators
cy.get('.bms-scoreboard__game-tile--mls')
.each(($el,index,$list) => {
cy.wrap($el).find('a')
.invoke('attr','href')
.then(href => {
cy.request(href)
.its('status')
.should('eq',200)
})
})
})
or move "find" into first selector
cy.get('.bms-scoreboard__game-tile--mls a')
.each($a => {
const href = $a.attr('href')
cy.request(href)
.its('status')
.should('eq', 200)
})
})
Related Topics
Chrome Autofill/Autocomplete No Value for Password
How to Add and Remove Classes in JavaScript Without Jquery
How to Access the Contents of an Svg File in an <Img> Element
How to Get Jquery.Trigger('Click'); to Initiate a Mouse Click
How to Maintain a Websockets Connection Between Pages
How to Detect Whether an Iframe Is Loaded
Sharing a Variable Between Multiple HTML Pages
Get Unique Selector of Element in Jquery
How to Determine Which Submit Button Was Pressed, Form Onsubmit Event, Without Jquery
Refresh a Div That Has a Google Ad Inside It
How to Open a New Window and Insert HTML into It Using Jquery
How to Format/Tidy/Beautify in JavaScript
How to Manually Trigger Validation with Jquery Validate
How to Reset a Form Using Jquery with .Reset() Method
Casperjs/Phantomjs Doesn't Load Https Page
Property 'Submit' of Object #<Htmlformelement> Is Not a Function