Javascript: replace a string in element.src attribute - javascript

Hi I am currently trying to replace a query string value in a a link's src attribute.
it works fine in firefox but not in ie.
example:
<a id="link" href="#" src="http://somedomain.com?id=123&size=20">link</a>
then on my js it looks kinda like this:
var link = document.getElementById('link');
link.src.replace('size=20', 'size=45');
in ie, it returns something like src is not an object error;
anyone kind enough to lend a hand?
also, i need this to be on native javascript so please don't suggest a framework as a solution thanks.

To get it to work in IE you're going to need to use link.setAttribute('src', ...).

use:
var link = document.getElementById('link');
var src = link.getAttribute("src").replace('size=20', 'size=45');
link.setAttribute("src", src);

Well, links (anchor elements) don't have a src attribute, I think that you want to change the href attribute:
var link = document.getElementById('link');
link.href = link.href.replace('size=20', 'size=45');

In your case the "src" attribute in your link is an expando attribute, since an anchor tag does not have a src.
When working with expando attributes, it's safest to set and get the values using the setAttribute('attributeName',***value*)** and getAttribute('attributeName') accessors.
To find out more about getAttribute and setAttribute you can check here:
https://developer.mozilla.org/en/DOM/element.getAttribute
https://developer.mozilla.org/en/DOM/element.setAttribute
To find out more about DHTML properties you can check the MSDN Resource here:
http://msdn.microsoft.com/en-us/library/ms533055%28VS.85%29.aspx
Example Code using getAttribute and setAttribute:
var link = document.getElementById('link');
var src = link.getAttribute('src');
link.setAttribute('src',src.replace('size=20','size=40'));

I believe getAttribute is more cross-browser friendly.
var link = document.getElementById('link');
var result = link.getAttribute("src").replace('size=20', 'size=45');
Also, the replace function returns a string. It doesn't operate on the string it is called against. This means you have to assign the result.
link.setAttribute("src", result);

Related

How does this href javascript logic work?

I made a mistake and forgot to use the attribute value in some code I was writing:
var link = document.getElementsByClassName("summary-title-link")[0],
ele = document.createElement("a");
ele.href = link;
and I was surprised to see that it still worked regardless.
In extension with this example below, I find it odd that I don't need to target the href attribute before using pathname? it seems to assume somehow that I want the pathname from the href attribute.
var link = document.getElementsByClassName("summary-title-link")[0].pathname;
"/test-link/1"
When you convert an anchor element to a string, you actually get the href value, or more precisely "the whole URL", and not the outerHTML as you would with most other elements, that's why it works
var href = document.getElementsByClassName("test")[0]; // DOM element
console.log(href.toString()); // gives you "http://google.com"
<a class="test" href="http://google.com">link</a>
This special behaviour for anchors is specified in the specification
HTMLHyperlinkElementUtils.toString()
Returns a USVString containing the whole URL.
It is a synonym for URLUtils.href, though it can't be used to modify the value.

Workaround for Href tag in firefox

I am using dojo for scripting.
I want to give the href tag which link to the local path of an excel file.
It works fine in IE ie., when I click on the link it asks for open/save/cancel.
But the same code isn't working for Firefox.
Is there any workaround for that?
I am writing the code, I look forward to your useful comments.
var href = dojo.place ('<"a href = /path/abc.csv"><Export></a>',dojo.body());
You have your quotes in the wrong place:
var href = dojo.place ('<Export>',dojo.body());
// Not here -------------^ ^
// Yes here ----------------------+
Your HTML syntax is invalid - it should be Export.
Probably because of the place of the quote. It should be after href
var href = dojo.place ('<a href = "/path/abc.csv">',dojo.body());
You are placed double quoate at anchor tag, it is wrong,
var href = dojo.place ('<"a href = /path/abc.csv"><Export></a>',dojo.body());
Your anchor tag href should be change as
var href = dojo.place ('<Export>',dojo.body());
Your quotes " ... " are not at correct place and syntax is not valid. it should be:
var href = dojo.place ('<Export>',dojo.body());
^
//note quotes here................^

Get an attributes value of the ALT attribute of a hyperlink

My a-tag (link) contains innerHTML which is an image like this:
.innerHTML = <img alt="hello world" src="/Content/Images/test.png">
How can I get the text of the alt attribute with JQuery?
You really don't need jQuery. If you have the a element you can do this:
// lets call the anchor tag `link`
var alt = link.getElementsByTagName('img')[0].alt; // assuming a single image tag
Remember attributes map to properties (most), and unless the property is changed, or the attribute, the two should reflect the same data (there are edge cases to this, but they can be handled case-by-case).
If you truly do need the attribute there is
var alt = link.getElementsByTagName('img')[0].getAttribute('alt');
Last scenario is if you only have the image tag as a string.
var str = '<img alt="hello world" src="/Content/Images/test.png">';
var tmp = document.createElement('div');
tmp.innerHTML = str;
var alt = tmp.getElementsByTagName('img')[0].alt;
If you must use jQuery (or just prefer it) then the other answer provided by Alexander and Ashivard will work.
Note: My answer was provided for completeness and more options. I realize the OP asked for jQuery solution and not native js.
Being $a your <a/> element.
Using jQuery you can do:
$("img", $a).first().attr("alt");
Or, using pure JavaScript:
var $img = $a.getElementsByTagName("img")[0];
console.log($img.alt);
​
See it here.
use this.
var altName=$('a img').attr('alt');

Javascript : get <img> src and set as variable?

If the img below is present
<img id="youtubeimg" src="http://i1.ytimg.com/vi/VK4ah66jBvE/0.jpg"/>
and the script is
<script>
var youtubeimgsrc = "something here"
document.write(''+youtubeimgsrc+'')
</script>
and the result should be http://i1.ytimg.com/vi/VK4ah66jBvE/0.jpg
what can i do to get the image source and set as a variable.
As long as the script is after the img, then:
var youtubeimgsrc = document.getElementById("youtubeimg").src;
See getElementById in the DOM specification.
If the script is before the img, then of course the img doesn't exist yet, and that doesn't work. This is one reason why many people recommend putting scripts at the end of the body element.
Side note: It doesn't matter in your case because you've used an absolute URL, but if you used a relative URL in the attribute, like this:
<img id="foo" src="/images/example.png">
...the src reflected property will be the resolved URL — that is, the absolute URL that that turns into. So if that were on the page http://www.example.com, document.getElementById("foo").src would give you "http://www.example.com/images/example.png".
If you wanted the src attribute's content as is, without being resolved, you'd use getAttribute instead: document.getElementById("foo").getAttribute("src"). That would give you "/images/example.png" with my example above.
If you have an absolute URL, like the one in your question, it doesn't matter.
How about this for instance :
var youtubeimgsrc = document.getElementById("youtubeimg").getAttribute('src');
If you don't have an id on the image but have a parent div this is also a technique you can use.
<div id="myDiv"><img src="http://www.example.com/image.png"></div>
var myVar = document.querySelectorAll('#myDiv img')[0].src
in this situation, you would grab the element by its id using getElementById and then just use .src
var youtubeimgsrc = document.getElementById("youtubeimg").src;
var youtubeimgsrc = document.getElementById('youtubeimg').src;
document.write(youtubeimgsrc);
Here's a fiddle for you http://jsfiddle.net/cruxst/dvrEN/
Use JQuery, its easy.
Include the JQuery library into your html file in the head as such:
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
(Make sure that this script tag goes before your other script tags in your html file)
Target your id in your JavaScript file as such:
<script>
var youtubeimcsrc = $('#youtubeimg').attr('src');
//your var will be the src string that you're looking for
</script>

How can I add "href" attribute to a link dynamically using JavaScript?

How can I add the href attribute to a link dynamically using JavaScript?
I basically want to add a href attribute to <a></a> dynamically (i.e. when the user clicks on specific image in the website).
So from:
<a>Link</a>
I need to go to:
Link
var a = document.getElementById('yourlinkId'); //or grab it by tagname etc
a.href = "somelink url"
I assume you know how to get the DOM object for the <a> element (use document.getElementById or some other method).
To add any attribute, just use the setAttribute method on the DOM object:
a = document.getElementById(...);
a.setAttribute("href", "somelink url");
document.getElementById('link-id').href = "new-href";
I know this is an old post, but here's a one-liner that might be more suitable for some folks.
First, try changing <a>Link</a> to <span id=test><a>Link</a></span>.
Then, add something like this in the javascript function that you're calling:
var abc = 'somelink';
document.getElementById('test').innerHTML = 'Link';
This way the link will look like this:
Link
More actual solution:
<a id="someId">Link</a>
const a = document.querySelector('#someId');
a.href = 'url';
I know there seems plenty good answers here, but none of them seemed simple enough for what I was "told" to do in the 2022 Udemy Web Development Bootcamp by Angela.
So I remembered how simple the use of scriplets was and figured to try it and it works just as well.
For those like me who are learning let me explain:
. - takes you to current URL
then static path
then dynamic variable generated for each post (its a blog website)
Read More
This is using JS inside an EJS page
same solution is also given in the solution lecture of the bootcamp here:
https://www.udemy.com/course/the-complete-web-development-bootcamp/learn/lecture/12385596#overview
Lecture 317
I came here because I wanted to dynamically set the link href after it's been clicked
<a id='dynamic'>link text</a>
document.getElementById("dynamic").addEventListener("click", onClick_dynamic)
function onClick_dynamic(e){
const nextPage = getNextPage()
document.getElementById("dynamic").href = _BASE_URL + "?nextPage=" + nextPage
// e.default processing sends user to href
}
Single line solution
<a id="yourId">Link</a>
document.querySelector("#yourId").href("URL")
enter code here javasicript added
var x = "www.google.com";
vay y = "550";
var z= x+y;
document.write('GONDER');

Categories

Resources