A string contains entire value of a html.i need to get the value of href tag i.e. src value.please help me to solve.
var alltext="a href="images/BGL30NA-10.JPG" target="""
var str=allText;
'a href="images/BGL30NA-10.JPG" target=""'.match(/href="(.*?)"/)[1]
try this regex .
if you using jQuery:
try this:
var href = $('a').attr('href')
but better if you have <a></a> with something id and then
var href = $('#youId').attr('href')
hope this may help you.
try this, it will gives the value of href in javascript, below work only if you assign id attribute in your anchor tag <a href="images\images1.jpg" id="image1">
for only value of href
document.getElementById("image1").getAttribute("href"); here is Jsfiddle
if you want to get full path then use this:
for full path of href document.getElementById("aaa").href; here is Jsfiddle
if you have any doubts, ask it in below comment. #sriram
Parse the string before and use appropriate DOM functions:
str = "hello, <b>my name is</b> jQuery.";
html = $.parseHTML( str );
# use $('a').attr('href') or any other selector here
The mandatory link to TONY THE PONY.
Related
Hello and thank you in advance for any and all assistance.
I'm trying to teach myself the basics of JavaScript before I start a bootcamp. In the Prep course we are asked to return the header, first link text and first link href using document.querySelector(). The course showed us how to do the header and I was able to get the first link text. What I cannot seem to figure out is how to return JUST the address and NOT the whole tag.
Some of the things I've tried:
document.querySelector('a href')
document.querySelector('a href=')
document.querySelector('a href=""')
document.querySelector('a').innerHTML
document.querySelector('a').innerText
document.querySelector('a href').innerHTML
document.querySelector('a href').innerText
Thanks again.
John
First Understand that href is an attribute, not an element, anchor is an element that accepts href as the attribute to get this attribute value you need to first get that anchor element then get its attribute value. For example:
let anchor = document.querySelector("a");
let url = anchor.getAttribute("href");
console.log(url)
`
let anchor = document.querySelector("a");
let url = anchor.getAttribute("href");
console.log(url)
<a href='https://stackoverflow.com/' tittle='stackOverflow'Stack Overflow></a>
`
document.querySelector("a").getAttribute("href")
You can try something like this, to bring any attribute of the anchor tag
document.querySelector('a').attributes.href.value
I have this javascript code:
<script ="text/javascript">
var newUrl=window.location.href;
var pathArray="";
pathArray=newUrl.substr(newUrl.lastIndexOf("?")+1);
</script>
I want to use the pathArray variable as a part of my href on the tag
This is my html code
<a href="game.html?"+pathArray>
<img src="img/RestartButton.png" style="position:absolute;
left:80px; top:220px">
</a>
but it seems like it doesn't read the value if the variable, but the name of it instead.
You're mixing your javascript into your HTML.
I believe your pathArray variable will also not contain what you are expecting.
Try this in your script tag:
var gamePath = "game.html?" + window.location.search.replace( "?", "" );
document.getElementById("gameAnchor").setAttribute("href", gamePath);
And add an id to your anchor:
<a href="#" id='gameAnchor'>
The javascript will get all GET parameters from the current url and then replace the href attribute in the element with an id of gameAnchor with your game.html concatenated with the GET parameters in the url.
You will have to use JavaScript for this as well. First give your anchor an ID:
<a id="myLink" href="game.html?"><img src="img/RestartButton.png" style="position:absolute; left:80px; top:220px"></a>
And then add following to your JavaScript code:
document.getElementById('myLink').href += pathArray;
The code will add the content of your string variable to href property of anchor element.
First, make the anchor easier to select by giving it an identifier.
(This is assuming there is more than one anchor on your page)
Then, in your script above include:
var anchor = document.getElementById("pathLink");
The anchor tag has a native href property, so assigning the new one is as easy as this:
Rewrite:
var anchor = document.getElementById("pathLink").href += pathArray;
It won't work like that. You will have to loop through the anchors your need using JavaScript.
This hasn't been tested. I'm assuming you want this to happen to more than one anchor link.
HTML:
<a class="updatethis" href="game.html">...</a>
...
<a class="udpatethis" href="game.html">...</a>
JavaScript:
var anchors = document.getElementsByTagName('a');
for (var i = 0, a; a = anchors[i++]; ) {
if (a.className === 'updatethis') {
a.href += window.location.search;
}
}
You can't place a javascript variable anywhere in html.
Instead you need to get the dom element through script and append the href attribute.
give your anchor an id or classname and try this as an example.
<a id="myLink" href="game.html">
<img src="img/RestartButton.png" style="position:absolute;left:80px; top:220px">
</a>
<script type="text/javascript">;
document.getElementById('myLink').href += window.location.search
</script>
You can access an attribute of an element in HTML. Although it's not really an HTML variable, it's roughly close to it. As you expect from a variable, you can get, set and remove it.
Element.getAttribute() :
getAttribute() returns the value of a specified attribute on the element. If the given attribute does not exist, the value returned will either be null or "" (the empty string); see Notes for details : https://developer.mozilla.org/en-US/docs/Web/API/Element/getAttribute
Example :
let myDiv = document.getElementById("myDiv");
console.log(myDiv.getAttribute("variable"))
<div class="div" id="myDiv" variable='test'</div>
Of course, you can set, or remove an attribute too :
Element.setAttribute()
Sets the value of an attribute on the specified element. If the
attribute already exists, the value is updated; otherwise a new
attribute is added with the specified name and value.
Element.removeAttribute()
Blockquote
removeAttribute removes an attribute from the specified element.
Note:
This being said, you will need javascript to interact with attributes. And that explains partially why it's not a "proper variable".
Think of using some template engine as undescore, moustache or doT.js. you can easily substitute html identifier or part of with template's data variables.
I want to replace an url in a href with a call of a function that needs to include the url.
example:
I have the following string:
Google
some other text
Wikipedia
I want to get back a string like this:
Google
some other text
Wikipedia
I have tested some ways with RegEx, but I'm not good with RegEx. Does anyone have a solution for my problem?
EDIT:
Sorry, I forgot to write. I'm building an appcelator application. I can't use jQuery or "document". I think the only way is a RegEx.
Give this regex a try:
/href="([^"]+)/g
Here is a sample of its usage (JsFiddle Demo)
var subject = 'Googlesome other textWikipedia';
var result = subject.replace(/href="([^"]+)/g, 'href="javascript:anyFunction(\'$1\')');
If you give your hrefs unique IDs you can do this:
var val = $("#myHref").attr("href");
$("#myHref").attr("href", "javascript:anyFunction('"+val+"');");
If you want to avoid unique IDs then you can do this (applied to all a's):
$("a").each(function() {
var val = $(this).attr("href");
$(this).attr("href", "javascript:anyFunction('"+val+"');");
});
If you want to avoid applying this to all hrefs you can give all the hrefs you want changed a class then use a selector like this: $(".hrefToModify")...
NEW:
If you can use javascript, then can you get access to the anchor tag itself? if so:
anchor_element.href = "javascript:anyFunction('" + anchor_element.href + "')";
OLD:
<a id="link1" href="www.google.com">Google</a>
some other text
<a id="link2" href="www.wikipedia.org">Wikipedia</a>
<script>
document.getElementById('link1').addEventListener('click', function(e) {
alert('hello');
e.preventDefault();
return false;
});
</script>
How can I use jQuery to get a string of text from the onclick attribute and set it as the href attribute.
Here's the fiddle I'm working with: http://jsfiddle.net/MBmt5/
I want to take only TrackPackage.asp?track=95213&ship=OTHER&ShippingMethod=3 from the onclick attribute and prop it to an href attribute
So that it would end up looking like this: http://jsfiddle.net/52Nha/
Unfortunately, I have no idea how to accomplish this. Can anybody help me? Must be compatible with jQuery 1.4.2. Thanks.
Update
Of course I'd begin with:
$(document).ready(function(){
$('span.trackpackagebutton').closest('a').removeAttr('href');
});
Ugly but I hope this will help you.
$('a').attr('href',
$('a')[0].getAttribute('onclick')
.replace("window.open('", '').split(',')[0].replace("'", ''))
.removeAttr('onclick');
Working demo - http://jsfiddle.net/MBmt5/5/
Note: Based on your markup structure you can use the right selector and reuse the above code.
E.g: The below code will execute this logic for all the anchors on the page which have onclick attribute which has window.open.
$('a[onclick^="window.open"]').each(function(){
$(this).attr('href',
this.getAttribute('onclick')
.replace("window.open('", '').split(',')[0].replace("'", ''))
.removeAttr('onclick');
});
Here's one way:
http://jsfiddle.net/MBmt5/2/
http://jsfiddle.net/GaZGv/1
var $a = $('span.trackpackagebutton').closest('a');
var href = $a.attr('onclick').split('(')[1].split(',')[0].replace(/'/g, '');
$a.attr('href', href).removeAttr('onclick');
alert(href)
I am trying to write a GreaseMonkey script in which I want to find all of the links that are relative links. It seemed to me that the way to do that would be to match the contents of href against /^https?:///.
But I find that when I access the anchor's href attribute, it's always normalized or cooked into a form that contains "http". That is, if the HTML contains:
<a id="rel" href="/relative/link">inner</a>
accessing
document.getElementById("rel").href
returns
http://example.com/relative/link
How can I access the raw data in the href attribute?
Alternately, is there a better way to find relative links?
Try the getAttribute method instead.
Typical. I figured it out myself almost immediately after posting the question.
instead of:
anchor.href
use:
anchor.getAttribute("href")
Of course, it took me longer to type in this answer than it took everyone else to answer it. (Damn, you people are fast.)
Here's a code snippet you could run to test.
const anchors = document.getElementsByTagName('a');
for (let anchor of anchors) {
let hrefFullPath = anchor.href;
let hrefRelativePath = anchor.attributes.href.value;
console.log('hrefFullPath', hrefFullPath);
console.log('hrefRelativePath', hrefRelativePath);
}
Let's say, you are at http://localhost:4200, and this is your document as you have shown in the question.
<a id="rel" href="/relative/link">inner</a>
This anchor's attribute value of href is:
document.getElementById('rel').attributes.href.value => /relative/link
And anchor's href value is:
document.getElementById('rel').href => http://localhost:4200/relative/link
I hope it helps.
Get the link dom and add attributes for same and append the actual link to same.
var hrefUrl = 'https://www.google.com/';
const link: HTMLLinkElement = dom?.createElement('link');
link.setAttribute('rel', 'canonical');
link.setAttribute('id', 'seo');
dom?.head?.appendChild(link);
dom?.getElementById('seo')?.setAttribute('href', hrefUrl);
// working
Hope this will work for dynamic links that to append for each dynamic pages under js / ts.