I want to grab the 'href' attribute from a link exactly as is in the source code so that I can locate the same link on another page. I thought that elementIdAttribute would grab the attribute and allow me to use it in a CSS locator, but for some reason elementIdAttribute completes relative URLs and appends slashes to the ends of some.
Here is the code I'm using to grab the 'href' attribute from the links on a page:
browser.elements("css selector", "div.field-item.even a", function(link_array) {
link_tot = link_array.value.length;
//Fetch the url from each 'a' tag in the content
for (var x = 0; x < link_tot; x++){
browser.elementIdAttribute(link_array.value[x].ELEMENT, "href", function(links) {
console.log(links.value);
urls.push(links.value);
});
}
})
If the 'href' property is href='node/16376', then the link my program ends up outputting is https://www.website.com/node/16376. I want it so that it only outputs "node/16376" without the full url being appended to it.
Is there any way to grab the 'href' attribute exactly as is (ie. relative URLs without extra slashes appended to them) so that it can be used in a CSS selector to find the same link on another page?
Why not just modify your result by using JavaScript String replace() Method :
urls.push(links.value.replace('https://www.website.com/',''));
Related
I am new to this site, and I know almost nothing about programming, so this question may have a simple answer.
I want to have links in my site that are able to grab a part of the current URL address to complete the href and send me to the desired webpage.
For example, let’s say that the webpage in my site I am viewing is:
https://www.example.com/notes/note-1
And then I have links in the same page like these ones:
https://www.example.com/editor1
https://www.example.com/editor2
Is there a way (java or jquery) that I can grab the last part of the path name (/note-1) to dynamically add it to my html links so the new addresses become?:
https://www.example.com/editor1/note-1
https://www.example.com/editor2/note-1
Now, I don’t need a code that appends “note-1” to the href, but that appends the ending of the current path—whatever it maybe (“/note-2, /note-3, etc.) to the href.
Thanks for your help.
You could implement it like so:
const idx = location.href.lastIndexOf('/');
const lastPart = idx !== -1 ? location.href.slice(idx + 1): "";
document.querySelectorAll('a').forEach(a=>a.href+=lastPart);
I'm trying to use window.location.pathname and injecting innerHTML to generate the file paths for an image so all I need to do is type fileName.png in a div in the html body and have the javascript generate the file path behind it so that it displays the image in the rendered website. This is for images that aren't stored in the same folder as the working file.
I've had mild success but it only works for one image per page which isn't very helpful.
I've gotten this code to work for one image per page:
<div class="picName">pic.png</div><div id=<"shortcut"></div>`
<script>
var relativePath = window.location.pathname;
var picName = document.getElementById('matts-shortcut').previousElementSibling.innerHTML;
document.getElementById("matts-shortcut").innerHTML =
'<src=\'/images' + relativePath + '/' + picName + '\'>';
</script>
The solution below pulls images names from with Divs using .querySelectorAll() which returns a DOM NodeList. The NodeList is useful because it has a forEach() method that can be used to loop over each item is the list. Loop over each list item using it's textContent property as the image name. Then you'll need to create a new image element for each image. To do that you can do something similar to this.
let relativePath = "https://dummyimage.com"; // replace the url with path name (maybe window.location.path)
// create a reference to the input list
// querySelectorAll return a NodeList
let inputNameList = document.querySelectorAll('.image-name');
// Loop through each image name and append it to the DOM
// the inputNameList (NodeList) has a "forEach" method for doing this
inputNameList.forEach((image) => {
let picName = image.textContent;
// Create a new image element
let imgEl = document.createElement('img');
// Set the src attribute of the image element to the constructed URL
// the name of the picture will be the div text content
// This is done with a template literal that you can learn about here:
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals
imgEl.src = `${relativePath}/${image.textContent}`;
// Now we have a real image element, but we need to place it into the DOM so it shows up
// Clear the image name
image.textContent = "";
// Place the image in the Div
image.appendChild(imgEl);
});
<div class="image-name">300.png</div>
<div class="image-name">200.png</div>
<div class="image-name">100.png</div>
<div class="image-name">400.png</div>
EDIT: In response to Ismael's criticism, I've edited the code slightly and commented every line so you can learn from this answer. There are two hyperlinks referenced in the code to help you think about coding in a modern way and so you can interpret modern code you read more easily.
About:
Arrow functions
Template Literals
Edit 2:
With further clarification, the answer has been amended to pull the image file names from Div elements already in the DOM.
Let ID equal your element's id
Call on:
document.getElementById(ID).src = "image_src"
When you want to change images, like an onclick action or as part of a function.
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.
I'm using a widget (Purechat) that allows customers and operators to communicate to each other. I've ran into an issue where anchors' href values inside this widget are being appended with "http://%20", thus making them unclickable to our users. We are investigating the code, however, I would like a quick fix for this by replacing all href contents that contain "http://%20" and replace that portion of the href with an empty string so my anchors work.
What would be the best way to go about this?
$('a').attr('href', function(index, value) {
return value.replace("//%20", "");
});
You can run a foreach jquery function which runs over every anchor whose href starts with that string, then cut it with substring method and set it's href value again.
This should work:
$("a[href^='http://%20']").each(function(){
var oldHref = $(this).attr('href');
var newHref = oldHref.substring(10, oldHref.length);
$(this).attr('href',newHref);
});
I need to set the href attribute of a link to point to a specific image, which has its id from the database set as its title. However, I am having trouble with trying to format the string to include a call to get the title attribute of the image.
Here is the base string:
$("#favoriteLink").hover(function() {
$(this).attr("href", '<%: Url.Action("FavoriteWallpaper", "Wallpaper", new{wallpaperId='+$(this).children.attr("title")+'}) %>');
});
favoriteLink is a div and the child is just one image.
Oh no, you can't mix server side code and javascript as you are trying to. How about this:
$('#favoriteLink').hover(function() {
var title = $(this).children.attr('title');
$(this).attr('href', function() {
var url = '<%= Url.Action("FavoriteWallpaper", "Wallpaper", new { wallpaperId= "_TITLE_TO_REPLACE_"}) %>';
return this.href.replace('_TITLE_TO_REPLACE_', title);
});
});
You're URL.Action is rendered serverside and your javascript client-side. You wont have access to dom elements when you're trying to build the link.
You should get the actual URL thats rendered in URL.Action and build the string client-side