How to add a href into a div with Javascript - 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>

Related

Add an img src to html from JavaScript correctly

I have created a script that creates an inner element in a HTML div element.
It works fine, but I think the way I did it using a string is not the most suitable in JavaScript.
HTML
<body>
<div class="chart-container">
<div class="chartlyrics">...</div><div class="chartlyrics box" id="powered_by"></div>
</div>
</body>
Where the "..." are is where I created the element.
Javascript
document.getElementsByClassName('chartlyrics')[0].innerHTML = '<img src="img/103-logo.jpg" class="" /><br />Powered by '
HTML Result:
<body>
<div class="chart-container">
<div class="chartlyrics"><img src="img/103-logo.jpg" class="" /><br />Powered by </div><div class="chartlyrics box" id="powered_by"></div>
</div>
</body>
How can I do this but without using a string when creating the element in JavaScript?
I tried this but it gives me a syntax error:
document.getElementsByClassName('chartlyrics')[0].innerHTML = ''
var img = document.getElementsByClassName('chartlyrics')
.appendChild(document.createElement("img"));
img.src = "img/103-logo.jpg"
img.class = ""
img.textContent = 'Powered by '
console.log(document.getElementsByClassName('chartlyrics')[0].innerHTML);
Result:
document.getElementsByClassName (...). appendChild is not a function
You need to access the first element of the HTMLCollection and append the <img> element to that. Furthermore, store the newly created element in a variable first so you can set properties before appending. To add a line break and text after the image, you can append a newly created <br> element and use .append to add text.
const parent = document.getElementsByClassName('chartlyrics')[0];
parent.innerHTML = '';
var img = document.createElement("img");
img.src = "img/103-logo.jpg"
img.setAttribute('class', "")
parent.appendChild(img);
parent.appendChild(document.createElement('br'));
parent.append('Powered by ');
However, finding every single element with a specificied class to obtain only one element is extremely wasteful. You should use document.querySelector to obtain the first element matching a selector.
const parent = document.querySelector('.chartlyrics');
parent.innerHTML = '';
var img = document.createElement("img");
img.src = "img/103-logo.jpg"
img.setAttribute('class', "")
parent.appendChild(img);
parent.appendChild(document.createElement('br'));
parent.append('Powered by ');

How i can insert an element in between in html using javascript?

I have to insert p tag in between other p tag in this example there only 3 p tag are there in my program there can be more so help me out.
**This is Html structure **
<div id="container">
<p>P1</p>
<p>p2</p>
<p>p3</p>
</div>
i want to insert a p tag in between using javascript . Thanks in advance.
You can insert elements through many different ways, but the most flexible is insertAdjacentHTML
and insertAdjacentElement
const secondP = document.querySelector("#container p:nth-child(2)");
const html = `<p>newly added p</p>`;
// add before the second p
secondP.insertAdjacentHTML("beforebegin", html);
// add after the second p
secondP.insertAdjacentHTML("afterend", html);
<div id="container">
<p>P1</p>
<p>p2</p>
<p>p3</p>
</div>
Based on your simplified question, a simpified answer:
const p = document.querySelector("#container p:nth-of-type(1)");
p.innerHTML += "<p>new p tag</P>";
Where as nth-of-type(1) selects the first p tag.
However, this question has been answered many times here, so please next time take some time to do some research.
I have a easy hack to do this in javscript:
document.getElementById("container").innerHTML += "<p>p4</p>";
However, you should be doing it by insertAdjacentElement
tempP = document.createElement('p');
tempP.innerText = "p4";
document.getElementById("container").insertAdjacentElement('afterend',tempP);

How to put <Tag> inside src / href

What I'm trying to accomplish is using DOM cloneNode() to get an element by tag name and clone it to another tag (inside URL).
So basically I want to put <tag> or <div class="tag">
inside the src or href attributes of another tag.
for example:
<body onload="myFunction()">
<script>
function myFunction() {
var itm = document.getElementsByTagName("tag1")[0].lastChild;
var cln = itm.cloneNode(true);
document.getElementsByTagName("tag2")[0].appendChild(cln);
}
</script>
<tag1>Hello.png</tag1>
<a href='http://example.com/<tag2></tag2>'> </a>
so the result should be:
<a href='http://example.com/Hello.png'> </a>
You could use Element.setAttribute() to update the href or src attributes, by replacing the string (i.e. <tag2></tag2>) using String.replace() with the innerHTML property of <tag1>.
Run the snippet below and press the button labeled "Copy". Note that encodeURI() is used because the <tag2> is actually encoded as far as the DOM property is concerned (i.e. it isn't a separate HTML tag).
document.addEventListener('DOMContentLoaded', function(DOMLoadEvent) {
document.getElementById('copy').addEventListener('click', copyTag1);
});
function copyTag1() {
var innerHTML = document.getElementsByTagName("tag1")[0].innerHTML;
var link = document.getElementById('link');
console.log('link.href before: ',link.href, 'innerhtml: ',innerHTML);
link.setAttribute('href', link.href.replace(encodeURI('<tag2></tag2>'),innerHTML));
console.log('link.href after: ',link.href);
}
<button id="copy">Copy</button>
<tag1>Hello.png</tag1>
<a id="link" href='http://example.com/<tag2></tag2>'> Example Link</a>

Display a link inside an if-condition using javascript

How can I display a href link inside an if condition using javascript?
<!DOCTYPE html>
<html>
<body>
<script>
function myFunction() {
var x = document.getElementById("fname");
if(x.value.indexOf("aaaa")>=0)document.getElementById("result").innerHTML= ""+ x.value + "" ;
else document.getElementById("result").innerHTML=x.value;
}
</script>
<form method="post" action="esegui.php">
Name<br><input type="text" id="fname" onkeyup="myFunction()">
</form>
<p id="result"></p>
</body>
</html>
You can create anchor tag using JavaScript following way:
var aTag = document.createElement('a');
aTag.setAttribute('href',"http://www.google.com");
aTag.innerHTML = "aaa";
document.body.appendChild(aTag);
Put above code in if condition will create anchor tag(link).
Although your question is a little bit confusing, I'll try to help you
If what you want is to create a specific link, do this:
var link = window.document.createElement("a");
var str = window.document.getElementById("theidofyourinput").value;
link.textContent = str;
link.href = 'http://www.linkofyourpage';
document.getElementsByTagName('body')[0].appendChild(link);
Try researching the createElement() method in JavaScript, calling it to create an anchor element in the body of your if statement e.g.
var myLink = document.createElement('a');
myLink.appendChild(document.createTextNode('link name')); //visible text
myLink.setAttribute('href', 'http://google.com'); //link href attribute
document.getElementById('someId').appendChild(myLink); //append the element
There are many ways to do this but you have not mentioned specific scenario so do like this:
In HTML:
<div id="test"></div>
In Java script:
var markup = "link";
var v = document.getElementById("test") ;
v.innerHtml(v );

Display html link with 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/

Categories