How to add onto a HTML attachment like href="" - javascript

So I ran up onto a problem, how would I add text into the HTML attachment href. So, and example:
...
How would I change it too:
...
But, what if I had mutiple of these with different href's:
...
...
...
How would I change them all?

href is called an attribute, and you can use .attr() to change it
If you want to add same prefix to all of them then
jQuery(function () {
$('a').attr('href', function (i, href) {
return 'http://google.com' + href;
});
})
Demo: Fiddle

First find all the elements you wish to change and put them into an array (below, I'm just using all anchor tags, but you could do getElementsByClassName and give them all some class as to not affect every anchor tag on the page), then loop through them and append the code.
(function () {
var anchors = document.getElementsByTagName("a");
for (var x = 0; x < anchors.length; x++) {
anchors[x].href = "http://google.com" + anchors[x].href;
}
})();

If you're appending the same string to the start of all anchor tags' HREF attribute within a particular DIV or other container (say it has ID myDiv), that's relatively easy:
$('#myDiv a').each(function(){
$(this).attr('href', 'http://google.com' + $(this).attr('href'));
});

Related

Replace multiple links

I'm trying to replace multiple links but only the first one is replaced,
all the other remain the same.
function rep(){
var text = document.querySelector(".link").querySelector("a").href;
var newText = text.replace(/http:\/\/test(.*)http:\/\/main(.*)com/, 'http://google$2com');
document.querySelector(".link").querySelector("a").href = newText;
}
Any suggestions?
It's multiple a href links inside .link elements which I'm talking about.
Your mistake is in using querySelector, so document.querySelector(".link").querySelector("a") literally translates to: get me the first a inside the first .link;
Use querySelectorAll; and you can combine the two selectors:
Vanilla JS:
[].forEach.call(document.querySelectorAll('.link a'), function(a){
a.href = a.href.replace(/http:\/\/test(.*)http:\/\/main(.*)com/, 'http://google$2com');
});
Or, since you'll select items more often, a little utility:
function $$(selector, ctx){
return Array.from((ctx && typeof ctx === "object" ? ctx: document).querySelectorAll(selector));
}
$$('.link a').forEach(function(a){
a.href = a.href.replace(/http:\/\/test(.*)http:\/\/main(.*)com/, 'http://google$2com');
})
Or in jQuery:
$('.link a').each(function(){
this.href = this.href.replace(/http:\/\/test(.*)http:\/\/main(.*)com/, 'http://google$2com');
});
This doesn't use JQuery, and I've changed your regular expression to something that made more sense for the example. It also works when you run the snippet.
function rep() {
var anchors = document.querySelectorAll(".link a");
for (var j = 0; j < anchors.length; ++j) {
var anchor = anchors[j];
anchor.href = anchor.href.replace(/http:\/\/test(.*)com/, 'http://google$1com');
}
}
rep();
a[href]:after {
content: " (" attr(href)")"
}
<div class="link">
What kind of link is this?
<br/>
And what kind of link is this?
<br/>
</div>
<div class="link">
What kind of link is this?
<br/>
And what kind of link is this?
<br/>
</div>
Edit: Expanded example showing multiple anchor hrefs replaced inside multiple link classed objects.
Edit2: Thomas example is a more advanced example, and is more technically correct in using querySelectorAll(".link a"); it will grab anchors in descendants, not just children. Edited mine to follow suite.
If you intend to only select direct children of link class elements, use ".link>a" instead of ".link a" for the selector.
Try using a foreach loop for every ".link" element. It seems that
every ".link" element have at least 1 anchor inside, maybe just one.
Supposing every .link element has 1 anchor just inside, something like
this should do:
$('.link').each(function(){
// take the A element of the current ".link" element iterated
var anchor = $(this).find('a');
// take the current href attribute of the anchor
var the_anchor_href = anchor.attr('href');
// replace that text and achieve the new href (just copied your part)
var new_href = the_anchor_href.replace(/http:\/\/test(.*)http:\/\/main(.*)com/,'http://google$2com');
// set the new href attribute to the anchor
anchor.attr('href', new_href);
});
I did't test it but it should move you to the way. Consider that we
could resume this in 3 lines.
Cheers
EDIT
I give the last try, looking at your DOM of the updated question and using plain javascript (not tested):
var links = document.getElementsByClassName('link');
var anchors = [];
for (var li in links) {
anchors = li.getElementsByTagName('A');
for(var a in anchors){
a.href = a.href.replace(/http:\/\/test(.*)com/, 'http://google$1com');
}
}
I suggest to read the following post comment for some cooler methods of looping/making stuff foreach item.
How to change the href for a hyperlink using jQuery

jQuery adding auto link to href attribute

HTML:
< p class="link-panel ">http:..www.google.com< /p ><br>
< a target="blank" href="">GO< /a>
jQuery:
var linkVal = new Array();
$('.link-panel').each(function(index){
linkVal[index] = $(this).text();
});
$('a').each(function(){
$(this).attr("href", linkVal);
});
I'm trying to get the text value from the P tag and append it to the href attribute in the link. I can do this for one, but I can't seem to work out how to make this work when there is more than one URL?
Thanks
You can iterate over the anchors and get the text from the previous paragraph
$('a').attr('href', function() {
return $(this).prev('p').text();
});
or iterate over paragraphs and set the href for the following anchor
$('.link-panel').each(function() {
$(this).next('a').attr('href', $(this).text());
});

Create "title" attribute using the text inside <a> tag?

Is it possible to take the text inside of an <a> tag and add it to title attribute of that tag using JavaScript?
For example:
Hello
I want the text "hello" to be the title attribute to the <a> tag. Like this:
Hello
Can this be done with JavaScript? Any help or direction would be appreciated.
In javascript, as requested:
var anchors = document.getElementsByTagName('a');
for(i = 0;i < anchors.length; i++) {
anchors[i].title = anchors[i].textContent;
}
http://jsfiddle.net/spencerooni/z97rc/
If you have an ID for the specific tag (e.g. ...):
$('#atag').attr('title', $('#atag').text());
or if you'd like to do this for all a tags:
$('a').each(
function() {
$(this).attr('title', $(this).text());
}
);
DEMO
$('a').each(function() {
var $this = $(this); /* slight optimisation over using $(this) twice */
$this.attr('title',$this.text());
});
In the most simple jQuery form:
$('a').attr('title', function(){ return $(this).text() })
jsFiddle example

changing/stripping off url pointed by image using javascript

Might be a very simple javascript injection question, but say I have an image html tag:
<img src="rainbow.gif">
I wanted to perform a javascript, such that when clicked on the image, it doesn't go to the myfile.htm. In other words, I wanted to strip the a href which surrounds the img. How can I do this in javascript? Say that I have the following to reference the image tag:
document.elementFromPoint(%f, %f)
f can be replaced by any double/float value
If you have a reference to the img element, then its parent (parentNode) will be the link (in the structure you've given). Three options:
Remove the link entirely
Disable the link
Change the link's href
1. Remove the link entirely
You can remove the link entirely by doing this:
var link = img.parentNode,
linkParent = link.parentNode;
linkParent.insertBefore(img, link);
linkParent.removeChild(link);
That uses parentNode to find the parent and grandparent, insertBefore to move the image, and removeChild to remove the link. Note that this assumes the image is the only thing in the link.
2. Disable the link
If you want to keep the link but render it useless, you can do this:
var link = img.parentNode;
if (link.addEventListener) {
link.addEventListener("click", function(event) {
event.preventDefault();
}, false);
}
else if (link.attachEvent) {
link.attachEvent("onclick", function() {
return false;
});
}
else {
link.onclick = function() {
return false;
}
}
3. Change the href of the link:
This is trivial, just set the href property of the link element (which you can get because it's the parent node of the image) to whatever you want:
img.parentNode.href = /* ...something else */;
For instance:
img.parentNode.href = "http://stackoverflow.com";
...would change the link to point to Stack Overflow.
Live example
Some references:
DOM2 Core
DOM2 HTML
DOM3 Core
HTML5 Web Application APIs
<a id="anchorWithImage" href="myfile.htm"><img src="rainbow.gif"></a>
Why not grab the anchor, then set its href to nothing:
var a = document.getElementById("anchorWithImage");
a.href = "javascript:void(0)";
Or grab it and set its click event to cancel the default action, which is to browse to the location of its href property
a.onclick = function(e) {
e.preventDefault();
}
Or do you want to grab all anchors that have an image as their child element, and strip out their href?
jQuery would make this easy, if that's an option for you
$("a").filter(function() {
return $(this).children("a").length === 1;
}).attr("href", "javascript:void(0)");
or
$("a").filter(function() {
return $(this).children("a").length === 1;
}).click(function() { return false; }); //returning false from jQuery handlers
//prevents the default action
EDIT
If you were to have a reference to the image, and wanted to set its parent's anchor's href, you'd grab it with the parentNode property:
var img = document.getElementById("imgId");
var a = img.parentNode;
a.href = "javascript:void(0)";
With jQuery you could use something similar to this
$("a").has("img").click(function(e).preventDefaults();});
Basically all this line does is identifies all tags within the document containing an tag disables standard event process
From your comment on another answer, it sounds like you actually want to change/eliminate the target of links at a specific position in the page. You could do something like this:
var el = document.elementFromPoint(10, 10);
while(el) {
if(el.nodeName.toLowerCase() == 'a')
el.href = 'javascript:';
el = el.parentElement;
}
This would loop up from the selected element, identify if the element is an anchor, and set the href to something that does nothing.
you can change the href of a tag on window load itself, so you need not worry when it is clicked.
window.onload = fundtion(){
var imgs = document.getElementsByTagName('img');
for(var i=0;i<imgs.length;i++){
var parentElem = imgs[i].parentNode;
if(parentElem.tagName === 'A')
parentElem.setAttribute("href", "javascript:void(0)");
}
};

Creating links for elements with a particular class with jQuery

How can I wrap every element belonging to a particular class with a link that is built from the text inside the div? What I mean is that I would like to turn:
<foo class="my-class>sometext</foo>
into
<a href="path/sometext" ><foo class="my-class>sometext</foo></a>
Url encoding characters would also be nice, but can be ignored for now if necessary.
EDIT: Just to clarify, the path depends on the text within the element
Use jQuery.wrap() for the simple case:
$(".my-class").wrap("<a href='path/sometext'></a>");
To process text inside:
$(".my-class").each(function() {
var txt = $(this).text();
var link = $("<a></a>").attr("href", "path/" + txt);
$(this).wrap(link[0]);
});
$(".my-class").each(function(){
var thisText = $(this).text();
$(this).wrap("<a></a>").attr("href","path/"+thisText);
});
you can wrap them inside anchor element like this:
$(document).ready(function(){
$(".my-class").each(function(){
var hr="path/"+$(this).text();
$(this).wrap("<a href='"+hr+"'></a>");
});
});
if you are opening links in same page itself then easier way than modifying dom to wrap elements inside anchor is to define css for the elements so that they look like links then handle click event:
$(".my-class").click(function(){
window.location.href="path/"+$(this).text();
});
$("foo.my-class").each(function(){
var foo = $(this);
foo.wrap("<a href='path/" + foo.Text() +"'>");
});
This ought to do it:
$('foo.my-class').each(function() {
var element = $(this);
var text = element.html(); // or .text() or .val()
element.wrap('');
});

Categories