How can I change a href attribute with javascript? - javascript

Helllo guys I have a read more link in my page but I want to change its link via javascrpt. I am having this link http://london/wa/al/Lists/Announcements/DispForm.aspx?ID=4 but this link does not work anymore and I do not have access to html anymore. So I need to change it to the following http://london/wa/meridianexpress/Lists/Announcements/DispForm.aspx?ID=4
how can I make this?

Perhaps you can try this:
window.onload = function ()
{
var allLinksOnPage = document.getElementsByTagName("a");
for (var i = 0; i < allLinksOnPage.length; i++) {
if (allLinksOnPage[i].href == 'http://london/wa/al/Lists/Announcements/DispForm.aspx?ID=4')
allLinksOnPage[i].href = 'http://london/wa/meridianexpress/Lists/Announcements/DispForm.aspx?ID=4';
}
}
Hope this will help...

you can add below line in any existing onload function or create one as below in any script file which you have access and already included in html
window.onload = function(){
document.getElementById("more").href="xyz.php";
}

Try this:
document.getElementById("yourhtmllikid").setAttribute("href", "http:...");

Related

JavaScript For Loop not returning anything (not running)?

Ok so, I've got this for loop in a script tag on my EJS page. The current code looks like this:
<script async>
var removeCartItemButtons = document.getElementsByClassName('btn-danger')
console.log(removeCartItemButtons)
var i;
for (i = 0; i < removeCartItemButtons.length; i++){
console.log('elem')
var button = removeCartItemButtons[i]
button.addEventListener('click', function() {
console.log('clicked')
})
}
</script>
The console.log for the removeCartItemButtons works but the console.log('elem') doesn't run. There are no errors in my cmd nor on the developer tools. I've looked online at different forums to find people doing similar things to me and their's work fine.
I've tried multiple things, and an extra notice is that this is inside the html file and not external.
The end goal of this for loop is to loop through every element with class 'btn-danger' and log when they are clicked.
Any help would be amazing!
try running document.getElementsByClassName('btn-danger') in the console.
Additional tip: there is a for of loop in js
check this: https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Statements/for...of
basically:
for(let button of removeCartItemButtons) {
button.addListener
}
I tried this code in Codepen and it worked. I rewrite your code but technically, just used a different syntax. "async" in your script tag can cause the problem, I can't be sure.
var buttons = document.querySelectorAll('.btn-danger');
[...buttons].forEach(button => {
console.log('elem')
button.addEventListener('click', function() {
console.log('clicked')
})
})
There must be an issue with your HTML code. Run the snippet below, it's working fine
var removeCartItemButtons = document.getElementsByClassName('btn-danger')
console.log(removeCartItemButtons)
var i;
for (i = 0; i < removeCartItemButtons.length; i++) {
console.log('elem')
var button = removeCartItemButtons[i]
button.addEventListener('click', function() {
console.log('clicked');
alert('clicked');
})
}
<button class='btn-danger'>Button</button>
<br/>
<button class='btn-danger'>Button</button>
<br/>
<button class='btn-danger'>Button</button>
<br/>
<button class='btn-danger'>Button</button>
removeCartItemButtons.length is 0 because when the snippet ran the DOM was not fully loaded.
Remove async and put your script at the end of your html.
Another option is to use an EventListener like onload to make sure your buttons exist before changing them.

Javascript that changes HTML code

Is it possible to make javascript to when you enter variables to add code to html..? I don't know English too good, so..I'm going to draw it!
Also, I don't want it to change everything, but I want it just to add that
info to the list..I have premade HTML page with linked CSS.
If you have any questions, please ask me, just help me.. :(
I know HTML and CSS, java..Not even a little bit.. :/
If you are here reading this, THANK YOU! <3
You have many options to add html to your page through JavaScript.
1) Simply create a div with an id
<div id="enterTextHere"></div>
2) Inside of your custom.js file or inside of <script></script>, you can use many different methods
Method 1 : Using innerHTML
var desiredElement = document.getElementById("enterTextHere");
desiredElement.innerHTML = "<p>I added text!</p>";
Method 2 : Using JQuery.append
$("#enterTextHere").append("I added text!");
I'm sure there are many more but without your specific code to reference this is the best I can do. Please use this link for your reference. It also has a lot of good information for the rest of your HTML journey. Enjoy! w3schools
Maybe something like this can help:
HTML:
<table class="table"><tr id="update-table"></tr></table>
<script>
(function(){
var updater = (function(){
function updater( options ){
this.table = options.table;
this.cells = this.table.querySelectorAll('.cell');
this.num_cells = this.cells ? this.cells.length : 0;
}
updater.prototype.update_element = function( index, value ){
this.cells[index].innerHTML = value;
};
updater.prototype.add_element = function(){
var td = document.createElement('td');
td.setAttribute('class','cell');
this.table.appendChild(td);
this.cells.push(td);
this.num_cells++;
};
return updater;
})();
window.updater = updater;
})();
var table, a, count = 0;
table = document.getElementById('update-table');
a = new updater({table:table});
for(var i = 0; i < 5; ++i){
a.add_element();
a.update_element(i,'info'+i);
}
</script>

Trying to replace every href on the document

i'm completely new to Javascript and I wanted to create an Greasemonkey Script that replaced "/text/othertext/" to "/text2/text3" on all the href elements of the document. That's what i came up with, and as expected, it doesn't work:
var links = document.getElementsByTagName('a');
for (i=0; i<links.length; i++)
{
var gethref = links[i].getAttribute('href');
gethref = gethref.replace(/text\/othertext/g,'text2\/text3');
links[i].setAttribute("href", gethref);
}
Thanks in advance!
Edit: ok, i know why my script is not working, but i don't know if it can be fixed, i'm trying to replace elements that load after the page is completely loaded (maybe with ajax?)
http://i.imgur.com/7n5V7Bi.png
This code works. Your code looks okay too. Perhaps you are loading the script before the document elements? Note how my elements are listed before my script:
link
link
<script>
var links = document.getElementsByTagName('a');
for(var i = 0; i < links.length; i++) {
var href = links[i].getAttribute('href');
href = href.replace('before', '#');
links[i].setAttribute('href', href);
}
</script>
Edit, based on your comments a dirty fix to cause delay in your app before running a script is to use the setTimeout function. To delay five seconds for example, you might use it like this:
link
link
<script>
setTimeout(function() {
var links = document.getElementsByTagName('a');
for(var i = 0; i < links.length; i++) {
var href = links[i].getAttribute('href');
href = href.replace('before', '#');
links[i].setAttribute('href', href);
}
}, 5000); // < --- note the time in ms here
</script>
Not too sure why your code wouldn't be working.
I've put together the following snippet which might help.
(function() {
var anchors = document.querySelectorAll('a');
for(var i = 0; i < anchors.length; i++) {
var newHref = anchors[i].getAttribute('href').replace(/text\/othertext/g,'text2\/text3');
anchors[i].setAttribute('href', newHref);
}
}());
a {
display: block;
}
<!DOCTYPE html>
<head></head>
<body>
Some link
Some other link
</body>
If you run this snippet you'll see only one anchor is updated correctly as intended.
Hope that helps you out!
The easiest solution would be to wrap your code in this:
window.onload = function(){
/* your code here */
};
This will ensure that your code (especially if you've placed your script in the of the document, won't load until the whole page is loaded (including text, images, etc).
window.onload = function() {
document.body.innerHTML = document.body.innerHTML
.replace('<a href="text/othertext/"', '<a href="text2/text3"');
};
<!DOCTYPE html>
<head></head>
<body>
Some link
Some other link
</body>

Can I access and then replace image based on src value?, using jQuery or otherwise

I have a hell CMS to work with and am wondering if i can do the following with jQuery (or just straight up JS)
images are being displayed with no ID's or classes and I'd like to replace images based on their src value
pseudo code would be something like...
find img where src = /img/00789-reg-1.jpg';
and replace src value with ='img/much-better-img.jpg';
thanks -
Each image is a part of array provided by document.images. You can loop through images to find the image with the source you need.
var index=0;
while(document.images[index]){
alert(document.images[index].src);
index++;
}
Yes you can:
jQuery('img[src=/img/00789-reg-1.jpg]').attr('src','img/much-better-img.jpg');
Could you use:
var images = document.images;
var iLength = images.length;
for (var i=0; i<iLength; i++){
thisImage = images[i];
if (thisImage.src == "theOneThatIWantToReplace"){
thisImage.src = "myNewSrc"
break;
}
}
At least this doesn't involve hefting JQuery around if you don't need it.
You can use the Attribute Starts With Selector to find your images, then do the replace:
$("img[src^='/img']").each(function(){
$(this).attr("src", "new image");
});
var replace = {
"/img/00789-reg-1.jpg": "img/much-better-img.jpg",
"/img/another.jpg": "img/another-img.jpg"
}
for (var src in replace){
$("img[src="+src+"]").attr("src", replace[src]);
}
You can get all images and then check source of it
$('img').foreach(function(o){
if (o.attr('src')=='oldfile')
o.attr('src', 'newfile');
});
This is long, but I don't know other way.

Is there a way to open all <a href> links on a page in new windows?

I have a bunch of <a href=".html"> links and want to make them all open in new windows.
I know I can do a search and replace all to add target="_blank" to all my <a href="..."> links.
However, is there a quick way, such as setting a CSS style, or adding some JavaScript code, to accomplish the same thing?
If you have a page consisting of only links, consider <base target="_blank">. This opens every link in a new window (but also includes the targets of forms, unless overridden with <form target="_self">.
As others have shown, without modifying the HTML source, you can use Javascript to iterate through all <a> tags and add the target attribute or add an event listener that sets the target attribute dynamically.
If you have jQuery it's simple
$("a").attr("target", "_blank");
Or regular Javascript
var links = document.links;
for (var i = 0; i < links.length; i++) {
links[i].target = "_blank";
}
As per #Lekensteyn's suggestion, without Javascript (added for Completeness)
<base target="_blank">.
CSS: No.
JavaScript: Delegate a click event, which adds a target="_blank" attribute on click of a link.
document.body.addEventListener(function(e) {
if (e.target.nodeName.toUpperCase() === 'A' && e.target.href) {
e.target.target = '_blank';
}
}, true);
Note: If the <a> element contains other elements, you might want to traverse the tree to find out whether an anchor element is clicked:
document.body.addEventListener(function(e) {
var target = e.target;
do {
if (target.nodeName.toUpperCase() === 'A' && target.href) {
target.target = '_blank';
break;
}
} while (target = target.parentElement);
}, true);
Or, if you're a jQuery-lover:
$('body').on('click', 'a', function(e) {
e.target.target = '_blank';
});
yep, u can add attribute with JS to all links in HTML document named 'target' with value '_blank' ;)
You could also open replace href's of all links from url to javascript:openInWindow(url) using this, and writing function in JS that opens new window and set's it's location to url ;) Google will help you with both.
Just add a html base element to the page using Javascript:
var e = document.createElement("base");
e.target = "_blank";
document.head.appendChild(e);
I've used pure vanilla JavaScript to create a script that makes all the links open in a new window.
<script type="text/javascript">
var all_links = document.querySelectorAll("a");
for (let index in all_links) {
try {
all_links[index].setAttribute("target", "_blank");
}
catch (error) {
//console.log(error);
}
}
</script>

Categories

Resources