Display html link with javascript - javascript

In some part of an html page, I have a link with the following code :
<a id="idname" class="classname" href="www.MySite.com/image-name.jpg">link-text</a>
I would like to automatically display the same link in another part of the same page by using a javascript.
What would be the script to insert in my page ?
Thank you in advance for any help in this matter.
Patrick

Try this:
myVar = document.getElementById("idname");
varLink = (myVar.attributes.href);

As son as you know the target id:
<div id="targetID">New Link: </div>
<div id="targetID2">New Link 2: </div>
And If you are using jQuery you can do like this:
var link = $("#idname").clone();
link.attr("id",link.attr("id") + (Math.random() * 10));
$("#targetID").append(link);
If not:
var link = document.getElementById("idname");
var newLink = document.createElement("a");
newLink.href = link.href;
newLink.className = link.className;
newLink.innerHTML = link.innerHTML;
newLink.id = link.id + (Math.random() * 10);
document.getElementById("targetID2").appendChild(newLink);
See this Example

<script>
window.onload = function() {
// get data from link we want to copy
var aHref = document.getElementById('idname').href;
var aText = document.getElementById('idname').innerHTML;
// create new link element with data above
var a = document.createElement('a');
a.innerHTML = aText;
a.href = aHref;
// paste our link to needed place
var placeToCopy = document.getElementById('anotherplace');
placeToCopy.appendChild(a);
}
</script>
Use code above, if you want just to copy your link to another place. JSFiddle

First, I want to point out that if you will just copy the element that will throw an error because the copied element will have the same id of the first one, so if you will create a copy of your element you don't have to give it the same id.
Try this code:
function copyLink(newDestination){
var dest=document.getElementById(newDestination);
var newLink=document.createElement("a");
var myLink=document.getElementsByClassName("classname")[0];
newLink.href=myLink.href;
newLink.className = myLink.className;
newLink.innerHTML = myLink.innerHTML;
newDestination.appendChild(newLink);
}
The newDestination parameter is the container element of the new Link.
For example if the new Container element has the id "div1":
window.onload = function() {
copyLink(div1);
}
Here's a DEMO.

Thank you very much to everyone for so many prompt replies.
Finally, I was able to use Jquery.
So, I tried the solution given by Andrew Lancaster.
In my page, I added the codes as follows, in this order :
1-
<span id="span1">
<a class="classname" href="www.MySite.com/image-name.jpg">link-text</a>
</span>
<p>
<span id="span2"></span>
</p>
and further down the page :
2-
<script type="text/javascript">
var span1val = $('#span1').html();
$('#span2').html(span1val);
</script>
Therefore, the two expected identical links are properly displayed.
But, unfortunately, I forgot to say something in my initial request:
the original link is in the bottom part of my page
I would like to have the duplicated link in a upper part of my page
So, would you know how to have the duplicated link above the original link ?
By the way, to solve the invalid markup mentioned by David, I just deleted id="idname" from the original link (that I could ignored or replaced by other means).
Thank you again in advance for any new reply.
Patrick

Using Jquery you could wrap your link in a span with an ID and then get the value of that ID and push it into another span id.
HTML
<span id="span1">
<a id="idname" class="classname" href="www.MySite.com/image-name.jpg">link-text</a>
</span>
<p>
<span id="span2"></span>
</p>
jQuery
var span1val = $('#span1').html();
$('#span2').html(span1val);
Example can be found here.
http://jsfiddle.net/3en2Lgmu/5/

Related

Loading an img object with a src in javascript

I want to add a thumbnail picture to a book's details, derived from the google books api, on the webpage. The code below will place the source code (api) for the appropriate book, first into the text field bookCover and then into the var copyPic, and then it should be copied into imgDisp, but it doesn’t. I can see that bookCover holds the right text, and have checked that copyPic holds the correct content.
<img id="imgDisp" src="http://books.google.com/books/content?
id=YIx0ngEACAAJ&printsec=frontcover&img=1&zoom=5&source=gbs_api" width="85" height="110"" />
$.getJSON(googleAPI, function(response) {
$("#title").html(response.items[0].volumeInfo.title);
$("#subtitle").html(response.items[0].volumeInfo.subtitle);
$("#author").html(response.items[0].volumeInfo.authors[0]);
$("#description").html(response.items[0].volumeInfo.description);
$("#version").html(response.items[0].volumeInfo.contentVersion);
$("#modeR").html(response.items[0].volumeInfo.readingModes.text);
$("#bookCover").html(response.items[0].volumeInfo.imageLinks.thumbnail);
var copyPic = document.getElementById('bookCover').innerHTML;
document.getElementById("imgDisp").src=copyPic;
Does anyone know why not? Or can I put the api details directly into imgDisp (can’t find such code syntax anywhere on the net)? Everything else is working fine. If I put a src in directly, then it works e.g.
document.getElementById("imgDisp").src = “http://.....api”
but not with a variable.
Without more info - eg, I can't see where the getJSON() function ends or what the URL's are, I can't see what the issue may be (except, perhaps, as in my last comment).
I idea seems ok, as I can replicate it (in a cut-down version of course):
function copyImageSource() {
let d = document.getElementById("bookCover").innerHTML;
document.getElementById("imgDisp").src = d;
}
<button onclick="copyImageSource();">Get image</button>
<div id="bookCover">https://duckduckgo.com/assets/icons/meta/DDG-icon_256x256.png</div>
<img id="imgDisp" src="">
I assume that this is the sort of thing you are trying to achieve?
(javascript -> jquery:
let copyPic = $("#bookCover").html();
$("#imgDisp").attr("src", copyPic);
)
Version using jquery:
function copyImageSource() {
let d = $("#bookCover");
d.html("http://books.google.com/books/content?id=YIx0ngEACAAJ&printsec=frontcover&img=1&zoom=5&source=gbs_api");
let dCopy = d.html().replace(/&/g, "&");
$("#imgDisp").attr("src", dCopy);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button onclick="copyImageSource();">Get image</button>
<div id="bookCover"></div>
<img id="imgDisp" src="https://www.picsearch.com/images/logo.png"/>
If you have jQuery you can easily do the following:
let source = 'https://img.com/image.png';
//to get the image object that has the above just do this:
let img = $('img[src="' + source + '"]');

How to add a href into a div with Javascript

I would like to add <a href='https://google.com'> after a <div>.
Here is what I've been trying:
http://jsfiddle.net/L29e4ftj/
Is there someone who could help me out please?
Thank you!
Is that how do you want this ?
<div id="autoComplete_list">
<div data-id="2" class="autoComplete_result">
<span class="autoComplete_highlighted">google</span>
</div>
</div>
<script>
var aUrl = document.createElement("a");
aUrl.setAttribute("href", "https://google.com");
aUrl.innerHTML = "<span class='autoComplete_highlighted'>Google</span>"
document.querySelector("#autoComplete_list").appendChild(aUrl);
</script>
Problem
The way you are selecting the div is slightly wrong.
You use getElementsByClassName() which returns a list of elements, not a single element, so you will get [div] instead of div.
Solution
You can either get the first element of that list:
document.getElementsByClassName("autoComplete_result")[0]
or use the simpler Document.querySelector:
document.querySelector(".autoComplete_result") (which returns only one element, not an array).
window.onload=function() {
// Notice the [0] which selects ONLY the first matched element
var mydiv = document.getElementsByClassName("autoComplete_result")[0];
var a = document.createElement('a');
a.setAttribute('href',"https://www.google.com");
a.innerText = "google link";
mydiv.appendChild(a);
}
Seems that the getElementsByClassName is not returning as expected, so the appendChild is not working. I tried using querySelector and is working fine. Take a look at the code snippet below:
var mydiv = document.querySelector('.autoComplete_result');
var a = document.createElement('a');
a.setAttribute('href',"https://www.google.com");
a.innerText = "google link";
mydiv.appendChild(a);
<body>
<div id="autoComplete_list">
<div data-id="2" class="autoComplete_result">
<span class="autoComplete_highlighted">goog</span>le
</div>
</div>
</body>

Replace text, and replace it back

I am using this code to replace text on a page when a user clicks the link. I would like a way to replace it back to the initial text using another link within the replaced text, without having to reload the page. I tried simply adding the same script within the replaced text and switching 'place' and 'rep_place' but it didn't work. Any ideas? I am sort of a novice at coding so thanks for any advice.
<div id="place">
Initial text here
<SCRIPT LANGUAGE="JavaScript">
function replaceContentInContainer(target,source) {
document.getElementById(target).innerHTML = document.getElementById(source).innerHTML;
}
</script>
<div class="text" onClick="replaceContentInContainer('place', 'rep_place')">
<u>Link to replace text</u></div></div>
<div id="replacements" style="display:none">
<span id="rep_place">
Replacement text here
</div></span>
Where do you store the original text? Consider what you're doing in some simpler code...
a = 123;
b = 456;
a = b;
// now how do you get the original value of "a"?
You need to store that value somewhere:
a = 123;
b = 456;
temp = a;
a = b;
// to reset "a", set it to "temp"
So in your case, you need to store that content somewhere. It looks like the "source" is a hidden element, it can just as easily hold the replaced value. That way values are swapped, not just copied. Something like this:
function replaceContentInContainer(target,source) {
var temp = document.getElementById(target).innerHTML;
document.getElementById(target).innerHTML = document.getElementById(source).innerHTML;
document.getElementById(source).innerHTML = temp;
}
So replace them you simply call:
replaceContentInContainer('place', 'rep_place')
Then to swap them back:
replaceContentInContainer('rep_place', 'place')
Note that this will replace the contents of the "source" element until they're swapped back again. From the current code we can't know if that will affect anything else on the page. If so, you might use a different element to store the original values. That could get complex quickly if you have a lot of values that you need to store.
How's this? I store the initial content in an element of an array called initialContent.
<div id="place">
Initial text here [replace]
</div>
<div id="replacements" style="display:none">
<span id="rep_place">
Replacement text here [revert]
</span>
</div>
<SCRIPT LANGUAGE="JavaScript">
var initialContent = [];
function replaceContentInContainer(target,source) {
initialContent[target] = document.getElementById(target).innerHTML;
document.getElementById(target).innerHTML = document.getElementById(source).innerHTML;
}
function showInitialContent(target) {
document.getElementById(target).innerHTML = initialContent[target];
}
</SCRIPT>
Working example: http://jsbin.com/huxodire/1/
The main changes I did were the following:
I used textContent instead of innerHTML because the later replaces the whole DOM contents and that includes removing your link to replace the text. There was no way to generate that event afterwards.
I closed the first div or else all the text would be removed with the innerText including the text that works as a link.
You said you wanted to replace back to the original text, so I used a variable to hold the last value only if this existed.
Hope this helps, let me know if you need more assistance.
The div tags were mixed up and wiping out your link after running it. I just worked with your code and showed how you could switch.
<div id="place">
Initial text here
</div>
<SCRIPT LANGUAGE="JavaScript">
function replaceContentInContainer(target,source) {
document.getElementById(target).innerHTML =
document.getElementById(source).innerHTML;
}
</script>
<div class="text" onClick="replaceContentInContainer('place', 'rep_place')">
<u>Link to replace text</u></div>
<div class="text" onClick="replaceContentInContainer('place', 'original_place')">
<u>Link to restore text</u></div>
<div id="replacements" style="display:none">
<span id="rep_place">
Replacement text here
</span>
<span id="original_place">
Initial text here
</span>
</div>

document.write erase buttons

I have a html page with buttons:
<INPUT TYPE=BUTTON VALUE="b1" onclick="init1()" >
init1:
document.innerHTML = "<object type='application/x-app' id='plugin' width='0' height='0' > </object>"
When I press the button b1 it erase the page and it just blank.
What am I doing wrong?
10xs,
Nir
Use appendChild on body instead of replacing (=). Your button will not get erased.
var object = document.createElement("object");
object.innerHTML = "<object...";
document.body.appendChild(object);
You need to adres proper anchor (place) in your code (in the DOM tree).
Try this instead:
var my_anchor = document.getElementById('element_in_DOM');
my_anhor.innerHTML = "<object type='application/x-app' id='plugin' width='0' height='0' > </object>"
Of course it erases the page. When you modify the .innerHTML of the -entire document-, and replace it with something else, that's what happens.
If you want to append that tag onto the document however, that's a different story. I would suggest the following to do such:
var your_element = document.createElement('object');
your_element.type = 'application/x-app';
your_element.id = 'plugin'
your_element.width = 0;
your_element.height = 0;
document.body.appendChild(your_element);​
DEMO

Javascript parse html, modify anchor tags that contain images

I have a vague idea on howto do this but I hoped more experienced devs might have a simpler solution.
I have a sting of HTML code from a JSON feed and where an "a" tag exists with an images inside the "a" tag I want to modify and add attributes. example:
<a style="color:000;" href="images/image.jpg">
<img width="100" height="20" src="images/image_thumb.jpg" />
</a>
I would like to change it to be:
<a style="color:000;" href="images/image.jpg" rel="lightbox" >
<img width="100" height="20" decoy="images/image_thumb.jpg" />
</a>
So adding an attribute to the "a" tag and modifying an attribute in the "img" tag. There maybe multiple links within the HTML code some with and without images and other HTML code surrounding them.
To be clear this is NOT modifying HTML already rendered on the page, this is modifying a string of code before it gets rendered.
To be extremely clear here is the JSON feed in question: http://nicekiwi.blogspot.com/feeds/posts/default?alt=json
The HTML code that contains the tags are found at "feed > entry > content > $t"
Am currently working with Mootools 1.3
Any ideas? Thanks.
First, put it in a new element that does not exist on the page, then modify it as usual:
var container = new Element("div", { html: yourHTML });
container.getElements("a img").forEach(function(img){
var link = img.getParent("a");
img.decoy = img.src;
img.removeAttribute("src");
link.rel = "lightbox";
});
Demo here: http://jsfiddle.net/XDacQ/1/
In straight JS
var a = document.createElement('div');
// put your content in the innerHTML like so
a.innerHTML = '<a style="color:000;" href="images/image.jpg"><img width="100" height="20" src="images/image_thumb.jpg" /></a>';
var b = a.firstChild;
b.rel = 'lightbox';
var c = b.firstChild;
c.setAttribute('decoy', c.src);
c.src = null;
// now you have your a tag
var newA = a.innerHTML;
Dumbest regexp
var string = '<a style="color:000;" href="images/image.jpg">="images/image_thumb.jpg" /></a>',
text = '';
text = string.replace('href', 'rel="lightbox" href');
text = text.replace('src', 'decoy');

Categories