I have a variable and I would like to add a link for its value. This below example only returns the html. How can I make this a clickable link when its returned?
var link = 'new link: <b>Clink Here</font></b>'
This should help you:
var myDiv = document.createElement("div");
var link = 'new link: <b>Clink Here</font></b>'
myDiv.innerHTML = link;
document.body.appendChild(myDiv);
For the id:
myDiv.id = "myLink";
alert(document.getElementById('myLink').innerHTML);
You need a container where the HTML will be placed. If you can use jQuery, this becomes very easy.
<div id="container"></div>
var link = '...';
$('#container').html(link);
Working sample: http://jsfiddle.net/mEjUg/
In jQuery:
$("<div />")
.html('new link: <b>Click Here</b>')
.appendTo("body");
Related
First, sorry I'm not good with javascript.
HTML:
<div id="Comment-ID">
<p class="comment-content">...</p>
</div>
The javascript: (Edit: Added the whole code)
<script type='text/javascript'>
function autoloadmore() {
var loadmoreClass = document.getElementsByClassName("loadmore")[0];
var loadmoreChild = loadmoreClass.querySelector('a')
if (loadmoreClass) {
loadmoreChild.click();
}
}
//<![CDATA[
function InsertarImagenVideo(id) {
var IDelemento = document.getElementById(id),
sustituir = IDelemento.innerHTML;
sustituir = sustituir.replace(/\[img\](.[^\]]*)\[\/img\]/ig, "<img class='img-comentarios' src='$1'\/>");
document.getElementById(id).innerHTML = sustituir;
}
//]]>
window.onload = function() {
autoloadmore();
setTimeout(function(){
InsertarImagenVideo('Comment-ID');
},3000);
};
</script>
"InsertarImagenVideo" replaces some text inside with an image. Instead of using it on "Comment-ID", I want to use it on "Comment-class".
Note: I can't edit the HTML.
I couldn't find anything when I searched, or maybe I didn't know how to look. Can someone help me with this?
You can use document.querySelector to select an element by class:
Update this line:
var IDelemento = document.getElementById(id),
to var IDelemento = document.querySelector(id),
and pass the class selector to your method InsertarImagenVideo
setTimeout(function(){
InsertarImagenVideo('.comment-content');
},3000);
I found a simple way to insert an image into the <p class="comment-content">...</p> element by grabbing the parent <div id="Comment-ID">.
I'm assuming that you need to grab the unique id to then access the inner <p> element to replace the existing text with an image. This code grabs the unique id element, then grabs the first <p> tag using .getElementsByTagName('p')[0]. One thing I did add is a proper image load script to update the <p> tag with the image once it has been loaded (maybe this removes the need for that setTimeout function you have?).
let classElement = document.getElementById("Comment-ID").getElementsByTagName('p')[0];
let imageObject = new Image();
imageObject.src = `https://www.clipartmax.com/png/full/1-14442_smiley-face-png-smiley-png.png`;
imageObject.onload = function() {
classElement.innerHTML = `<img id="myImg" src="${imageObject.src}" />`;
let imageElement = document.getElementById(`myImg`);
imageElement.width = 100;
imageElement.height = 100;
};
Here's a JSFiddle demo of the upper code in action.
Hope this helps :)
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
I'm trying to build some HTML using jquery and then inject that html into some div on my page. I want to build an anchor element. The href, and the label of my anchor element come from javascript variables. I'm trying to do it like this:
$(function(){
var href = 'http://testing123.com';
var label = 'Anchor label';
var anchor_element = '' + label + '';
});
But this doesn't work. Any idea how I can properly construct my anchor element in javascript/jquery please.
You have to append the result to the DOM. add this line at the end.
$('body').append(anchor_element);
You can ofcourse replace 'body' with any other selector as you like.
$(function(){
var href = 'http://testing123.com';
var label = 'Anchor label';
var anchor_element = '' + label + '';
$('body').append(anchor_element); // add the element to <body>
});
working jsFiddle
Using jquery syntax:
$('<a/>', {
href: 'http://testing123.com',
text: 'Anchor label'
}).appendTo('body');
You can do this:
var href = 'http://testing123.com';
var label = 'Anchor label';
// Create a dynamic anchor element and set the href and label
var $anchor_element = $('<a/>', {
href: href,
text: label
});
// Append the newly created element to DOM,
// here we are appending it to the body
$('body').append($anchor_element);
FIDDLE DEMO
What ever you have write is working fine,But You forgot to append it to the target.
var href = 'http://testing123.com';
var label = 'Anchor label';
var anchor_element = '' + label + '';
$('#target').append(anchor_element);
Working Fiddle
I have made a Javascript link maker...
document.write('http://imgur.com'.link('http://www.imgur.com'));
How I can make this open the link target in a new window, like target="blank"?
Here's a new "link builder" to override the built in link function, and its usage:
function mylink(url) {
return "" + this + ""
}
String.prototype.link = mylink
document.write('http://imgur.com'.link('http://www.imgur.com'));
You can use a function to add a link to a container. E.g.:
<div id="container"></div>
And the Javascript is:
addLink('value', 'http://jsfiddle.net');
function addLink(text, url){
var mydiv = document.getElementById("container");
var a = document.createElement('a');
a.setAttribute('href',url);
a.setAttribute('target','_blank');
a.innerHTML = text;
mydiv.appendChild(a);
}
This is a working JSFiddle JSFiddle
I have a string for a title and a string for a link. I'm not sure how to put the two together to create a link on a page using JavaScript. Any help is appreciated.
The reason I'm trying to figure this out is because I have an RSS feed and have a list of titles ands URLs. I would like to link the titles to the URL to make the page useful.
I am using jQuery but am completely new to it and wasn't aware it could help in this situation.
<html>
<head></head>
<body>
<script>
var a = document.createElement('a');
var linkText = document.createTextNode("my title text");
a.appendChild(linkText);
a.title = "my title text";
a.href = "http://example.com";
document.body.appendChild(a);
</script>
</body>
</html>
With JavaScript
var a = document.createElement('a');
a.setAttribute('href',desiredLink);
a.innerHTML = desiredText;
// apend the anchor to the body
// of course you can append it almost to any other dom element
document.getElementsByTagName('body')[0].appendChild(a);
document.getElementsByTagName('body')[0].innerHTML += ''+desiredText+'';
or, as suggested by #travis :
document.getElementsByTagName('body')[0].innerHTML += desiredText.link(desiredLink);
<script type="text/javascript">
//note that this case can be used only inside the "body" element
document.write(''+desiredText+'');
</script>
With JQuery
$(''+desiredText+'').appendTo($('body'));
$('body').append($(''+desiredText+''));
var a = $('<a />');
a.attr('href',desiredLink);
a.text(desiredText);
$('body').append(a);
In all the above examples you can append the anchor to any element, not just to the 'body', and desiredLink is a variable that holds the address that your anchor element points to, and desiredText is a variable that holds the text that will be displayed in the anchor element.
Create links using JavaScript:
<script language="javascript">
<!--
document.write("<a href=\"www.example.com\">");
document.write("Your Title");
document.write("</a>");
//-->
</script>
OR
<script type="text/javascript">
document.write('Your Title'.link('http://www.example.com'));
</script>
OR
<script type="text/javascript">
newlink = document.createElement('a');
newlink.innerHTML = 'Google';
newlink.setAttribute('title', 'Google');
newlink.setAttribute('href', 'http://google.com');
document.body.appendChild(newlink);
</script>
There are a couple of ways:
If you want to use raw Javascript (without a helper like JQuery), then you could do something like:
var link = "http://google.com";
var element = document.createElement("a");
element.setAttribute("href", link);
element.innerHTML = "your text";
// and append it to where you'd like it to go:
document.body.appendChild(element);
The other method is to write the link directly into the document:
document.write("<a href='" + link + "'>" + text + "</a>");
<script>
_$ = document.querySelector .bind(document) ;
var AppendLinkHere = _$("body") // <- put in here some CSS selector that'll be more to your needs
var a = document.createElement( 'a' )
a.text = "Download example"
a.href = "//bit\.do/DeezerDL"
AppendLinkHere.appendChild( a )
// a.title = 'Well well ...
a.setAttribute( 'title',
'Well well that\'s a link'
);
</script>
The 'Anchor Object' has its own*(inherited)* properties for setting the link, its text. So just use them. .setAttribute is more general but you normally don't need it. a.title ="Blah" will do the same and is more clear!
Well a situation that'll demand .setAttribute is this: var myAttrib = "title"; a.setAttribute( myAttrib , "Blah")
Leave the protocol open.
Instead of http://example.com/path consider to just use //example.com/path.
Check if example.com can be accessed by http: as well as https: but 95 % of sites will work on both.
OffTopic: That's not really relevant about creating links in JS
but maybe good to know:
Well sometimes like in the chromes dev-console you can use $("body") instead of document.querySelector("body") A _$ = document.querySelectorwill 'honor' your efforts with an Illegal invocation error the first time you use it. That's because the assignment just 'grabs' .querySelector (a ref to the class method). With .bind(... you'll also involve the context (here it's document) and you get an object method that'll work as you might expect it.
Dynamically create a hyperlink with raw JavaScript:
var anchorElem = document.createElement('a');
anchorElem.setAttribute("href", yourLink);
anchorElem.innerHTML = yourLinkText;
document.body.appendChild(anchorElem); // append your new link to the body
A dirty but quick way to create elements:
const linkHTML = `<a
class="my-link"
style="position: absolute; right: 0"
href="https://old.reddit.com"
title="Go to old reddit"
>
Old Reddit
</a>`;
// create element
const linkEl = strToElement(linkHTML);
// add element to document.body
document.body.appendChild(linkEl);
// utility function that converts a string to HTML element
function strToElement(s) {
let e = document.createElement('div');
const r = document.createRange();
r.selectNodeContents(e);
const f = r.createContextualFragment(s);
e.appendChild(f);
e = e.firstElementChild;
return e;
}
You paste this inside :
Click here