JavaScript convert string hrefs into onClicks - javascript

I've got strings with multiple standard links like
Name of Link
and I'm trying to turn them into
<a onClick="myFunc('http://example.com','Name of Link')">Name of Link</a>
or even just:
<a onClick="myFunc('http://example.com')">Name of Link</a>
would be great if the former was unnecessarily difficult. The links are being dynamically inserted into the DOM so event handlers won't do.

You need event handlers that prevents the default action and get the href
var anchors = document.getElementsByTagName('a');
for (var i=anchors.length; i--;) {
anchors[i].addEventListener('click', func, false);
}
function func(e) {
e.preventDefault();
var href = this.getAttribute('href'),
text = this.innerText;
myFunc(href, text);
}
FIDDLE
If you have to work with strings, you can do something like this
var str = 'Name of Link 1<br />Name of Link 2<br />Name of Link 3<br />Name of Link 4';
var parser = new DOMParser();
var doc = parser.parseFromString(str, "text/html");
var anchors = doc.getElementsByTagName('a');
for (var i=anchors.length; i--;) {
var href = anchors[i].getAttribute('href'),
text = anchors[i].innerText;
anchors[i].setAttribute('onclick', "myFunc('"+href+"', '"+text+"')");
anchors[i].removeAttribute('href');
}
str = doc.body.innerHTML;
document.body.innerHTML = str;
function myFunc(href, text) {
alert(href + ' - ' + text);
}

You can do like this
HTML
<a href="http://example.com" onclick="myFunction(this.href,this.textContent)">
My link
</a>
JS
function myFunction(getAttr,text){
console.log(getAttr,text);
}
EXAMPLE
EDIT
if you are looking to prohibit href action then you have to use
event.preventDefault();
Updated JS
function myFunction(event,getAttr,text){
event.preventDefault();
console.log(getAttr,text);
}
UPDATED JSFIDDLE

Append your string in a temporary element and manipulate it as explained by adeneo
Try this:
var str = 'Name of Link';
var elem = document.createElement('div');
elem.innerHTML = str;
var targetEleme = elem.getElementsByTagName('a')[0];
targetEleme.addEventListener('click', function(e) {
e.preventDefault();
var href = this.getAttribute('href'),
text = this.innerText;
myFunc(href, text);
});
document.body.appendChild(targetEleme);
function myFunc(href, text) {
alert('HREF: ' + href + ' TEXT: ' + text);
}
Fiddle here

Related

Modifying URL with javascript

I have some simple code that allows you to enter Amazon isbns/asins and converts them to hyperlinks. These hyperlinks are Amazon.com searches for the said isbn/asin.
Example pic: http://imgur.com/a/rYgYt
Instead of the hyperlink being a search I would like the link to go directly to the products offer page.
The desired link would be as follows:
https://www.amazon.com/gp/offer-listing/ASIN/ref=dp_olp_used?ie=UTF8&condition=used
"ASIN" would be where the ASIN/ISBN would need to be populated to generate the link, for example:
Im asking if someone could help modify my existing code to create the change. My skills lack the ability to implement the change. The existing code is as follows:
<html>
<head>
</head>
<div><b>ISBN Hyperlinker</b></div> <textarea id=numbers placeholder="paste isbn numbers as csv here" style="width:100%" rows="8" >
</textarea> <div><b>Hyperlinked text:</b></div> <div id="output" style="white-space: pre"></div>
<input type="button" id="button" Value="Open All"/>
<script>
var input = document.getElementById('numbers');
var button = document.getElementById('button');
var output = document.getElementById('output')
var base =
'https://www.amazon.com/s/ref=nb_sb_noss?url=search-alias%3Daps&field-keywords='
var urls = []
//adding an event listener for change on the input box
input.addEventListener('input', handler, false);
button.addEventListener('click', openAllUrls, false);
//function that runs when the change event is emitted
function handler () {
var items = input.value.split(/\b((?:[a-z0-9A-Z]\s*?){10,13})\b/gm);
urls=[];
// Build DOM for output
var container = document.createElement('span');
items.map(function (item, index) {
if (index % 2) { // it is the part that matches the split regex:
var link = document.createElement('a');
link.textContent = item.trim();
link.setAttribute('target', '_blank');
link.setAttribute('href', base + item);
container.appendChild(link);
urls.push(base + item);//add the url to our array of urls for button click
} else { // it is the text next to the matches
container.appendChild(document.createTextNode(item))
}
});
// Replace output
output.innerHTML = '';
output.appendChild(container);
}
function openAllUrls(){
for(var i=0; i< urls.length; i++){//loop through urls and open in new windows
window.open(urls[i]);
}
}
handler(); // run on load
</script>
</html>
to modify output URL, replace
var base = ".....';
with
var basePrefix = 'https://www.amazon.com/gp/offer-listing/';
var baseSuffix = '/ref=dp_olp_used?ie=UTF8&condition=used';
and replace
base + item
with
basePrefix + item + baseSuffix

How can I create a link based on this format: google->someword?

I want to create links, based on a specific format.
When I type this:
google->apple
I want get get this link:
https://www.google.hu/search?q=apple
I tried this way, but unfortunately it is not working:
//Intelligent actions start
function replace(){
var str = $('.smile').html();
var re = /google->([^ \n$]+)/g;
var url = "https://www.google.hu/search?q=" + re.exec(str)[1];
}
//Intelligent actions end
Update
Based #vinayakj answer, I start create a solution for this:
//Intelligent actions start
function googleSearch(val){
var url = "https://www.google.hu/search?q=" + val.split('->')[1];
alert(url)
//location.href = url;
}
$( document ).ready(function() {
googleSearch($('.comment-content p').text())
$( ".comment-content p" ).replaceWith( "<a href='url'>url</a>" );
});
//Intelligent actions end
And looks like replacewith function reaplce all content in
.comment-content p
with:
url
And this function it has some problem:
Reaplce all text even if dosen't find this sting in div:
google-->some word
The link is absolute incorrect becouse I get back this value everywhere:
url
What am I doing wrong?
function googleSearch(val){
var url = "https://www.google.hu/search?q=" + val.split('->')[1];
alert(url)
location.href = url;
}
<input onchange="googleSearch(this.value)" type=text>
Here is the final solution after all your comments
var urls = {
"google":"https://google.com/search?q=#",
"bing":"https://....q=#&bla=bla"};
function getUrl(str) {
var parts = str.split("->");
var url = urls[parts[0]].replace("#",encodeURI(parts[1]));
return = $("<a/>",{href: url, class:parts[0]+"-search"}).text("Keresés ..."+parts[1]);
}
$(function() {
$("div.comment-content > p.smile").each(function() {
var $link = getLink($(this).text());
$(this).html($link);
});
});
Old answer
var urls = {
"google":"https://google.com/search?q=#",
"bing":"https://....q=#&bla=bla"};
function getUrl(str) {
var parts = str.split("->");
return urls[parts[0]].replace("#",parts[1]);
}
window.onload=function() {
document.getElementById("myForm").onsubmit=function() {
var str = document.getElementById("q").value;
var url = getUrl(str);
if (url) alert(url); // location.href=url;
return false; // cancel the submit
}
}
<form id="myForm">
<input id="q" type="text">
</form>
I found the solution, but thanks for everybody:
$("div.comment-content > p.smile").each(function(){
var original = $(this).text();
var replaced = original.replace(/google->([^.\n$]+)/gi, '<a class="google-search" href="https://www.google.hu/search?q=$1" target="_blank">Keresés a googleben erre: $1</a>' );
$(this).html(replaced);
console.log("replaced: "+replaced);
});
$("a.google-search").each( function() {
this.href = this.href.replace(/\s/g,"%20");
});

How to get function arguments' text value in js?

I find some code:
<a onclick="return dosomething('1234567')"></a>
I want to get the "1234567", Is there anyway to get it without Regular expressions ?
The code is in the html on www.xxxxxxxx.com and I can't change, the argument in dosomething function is data used as id.I want collect the id information.
So the html might be
<a onclick="return dosomething('1')"></a>
<a onclick="return dosomething('2')"></a>
<a onclick="return dosomething('3')"></a>
<a onclick="return dosomething('4')"></a>
I want run some js code in browser's console to get data like "1","2","3","4"
I have used jquery get the html like
$("a")
Then I don't know how to get the argument in "dosomething function". It is only a text to me.
Try this
$(function () {
var txt = $('a[onclick^="return dosomething("]').map(function () {
return this.getAttribute('onclick').match(/'.*'/)[0];
}).get().join(",");
alert(txt);
});
EDIT: without RegExp
$(function () {
var txt = $('a[onclick^="return dosomething("]').map(function () {
var attr = this.getAttribute('onclick');
return attr.substring(attr.indexOf("'"), attr.lastIndexOf("'") + 1);
}).get().join(",");
alert(txt);
});
try this
$(document).ready(function(){
var new_text = "";
$("a").each(function(){
var str = $(this).attr("onclick");
var newtext = str.substring(str.lastIndexOf("(")+1,str.lastIndexOf(")"));
if(new_text=="")
new_text += newtext;
else
new_text += ","+newtext;
});
alert(new_text);
console.log("New Text : "+new_text);
});
FIDDLE DEMO

if text contains '#' change color of '#'

I'm looking for a solution for my problem.
I have a paragraph with some text from a twitter tweet. Now I would like to change all the '#'s to a color.
This is what I do to look for '#'s in my text:
if (status.indexOf("#") >= 0)
{
}
But now how can I change the color of the #? (Add a span and class or something ...)
The status is a variable with content for ex. like this:
Dita Von Teese draagt geprinte 3D-jurk <a target="_blank" href="http://t.co/s2y6b21S0I">http://t.co/s2y6b21S0I</a> via #<a target="_blank" href="http://twitter.com/Knackweekend">Knackweekend</a>
Without seeing your HTML, the best I can offer is a simple replace, and I'm assuming that status is a jQuery collection of HTML elements/nodes:
status.html(function(i,h){
return h.replace(/#/g,'<span class="atSign">#</span>');
});
Coupled with the CSS:
.atSign {
color: #f90;
}
Updated, since status appears to be a string (from the comments, below):
var status = '<a target="_blank" href="t.co/s2y6b21S0I">http://t.co/s2y6b21S0I</a>; via #<a target="_blank" href="twitter.com/Knackweekend">Knackweekend</a>',
newStatus = status.replace(/#/g,'<span class="atSign">#</span>');
console.log(newStatus);
JS Fiddle demo.
To colour the # and the following a element, with CSS:
.atSign,
.atSign + a {
color: #f90;
}
JS Fiddle demo.
To wrap the # and the following a element within the span:
var status = '<a target="_blank" href="t.co/s2y6b21S0I">http://t.co/s2y6b21S0I</a>; via #<a target="_blank" href="twitter.com/Knackweekend">Knackweekend</a>',
newStatus = status.replace(/(#.+<\/a>)/g,function(a){
return '<span class="atSign">' + a + '</span>';
});
console.log(newStatus);
JS Fiddle demo.
References:
html().
JavaScript regular expressions.
String.replace().
You can insert a new span on same index and remove the existing item in that index.
Yes, you will need to wrap the # in a span with a class so that you can change the colour with CSS.
You could manipulate the DOM like this
CSS
.atSign {
color: #f90;
}
HTML
<div id="status">Some # text <div>that # contains#what</div>we will# demonstrate</div>
Javascript
/*jslint maxerr: 50, indent: 4, browser: true */
(function () {
"use strict";
function walkTheDOM(node, func) {
func(node);
node = node.firstChild;
while (node) {
walkTheDOM(node, func);
node = node.nextSibling;
}
}
function getTextNodes(element) {
var nodes = [];
walkTheDOM(element, function (node) {
if (node.nodeType === 3) {
nodes.push(node);
}
});
return nodes;
}
function highlight(element, string, classname) {
var nodes = getTextNodes(element),
length = nodes.length,
stringLength = string.length,
i = 0,
index,
text,
newContent,
span,
node;
while (i < length) {
node = nodes[i];
newContent = document.createDocumentFragment();
text = node.nodeValue;
index = text.indexOf(string);
while (index !== -1) {
newContent.appendChild(document.createTextNode(text.slice(0, index)));
text = text.slice(index + stringLength);
span = document.createElement("span");
span.className = classname;
span.appendChild(document.createTextNode(string));
newContent.appendChild(span);
index = text.indexOf(string);
}
newContent.appendChild(document.createTextNode(text));
node.parentNode.replaceChild(newContent, node);
i += 1;
}
}
highlight(document.getElementById("status"), "#", "atSign");
}());
On jsfiddle
How can you use this with your HTML string you ask?
Javascript
var div = document.createElement("div"),
html;
div.innerHTML = 'Dita Von Teese draagt geprinte 3D-jurk <a target="_blank" href="http://t.co/s2y6b21S0I">http://t.co/s2y6b21S0I</a> via #<a target="_blank" href="http://twitter.com/Knackweekend">Knackweekend</a>';
highlight(div, "#", "atSign");
html = div.innerHTML;
console.log(html);
Output
Dita Von Teese draagt geprinte 3D-jurk <a target="_blank" href="http://t.co/s2y6b21S0I">http://t.co/s2y6b21S0I</a> via <span class="atSign">#</span><a target="_blank" href="http://twitter.com/Knackweekend">Knackweekend</a>
On jsfiddle
And no jquery or regexs in sight :)

javascript extract html block from string

I have a string extracted from a div and stored in variable "str". I now need to extract the ... subset of it.
str = '<div id="xyz"><p>This is a paragraph</p><img src="http://bs.serving-sys.com/BurstingPipe/adServer.bs?cn=bsr&FlightID=2997227&Page=&PluID=0&Pos=9088" border=0 width=300 height=250></div>';
Thanks in advance for any help with this.
You could try something like the below:
var a = $(str).find('a').html();
make it innerHTML of a temporary div.
use getElementsByTagName("A") to retreive all "A" nodes.
get their HTML .
Here is a running example : http://jsfiddle.net/3fZch/
var str = '<div id="xyz"><p>This is a paragraph</p><img src="http://bs.serving-sys.com/BurstingPipe/adServer.bs?cn=bsr&FlightID=2997227&Page=&PluID=0&Pos=9088" border=0 width=300 height=250></div>';
var newElem = returnTheParentNode(str);
var anchors = newElem.getElementsByTagName('A');
/* anchors has all the a tags of the html string */
for(var i = 0 ; i < anchors.length ; i++)
{
var aHTML = getHTML(anchors[i]);
alert(aHTML);
}
function returnTheParentNode(htmlStr)
{
var myCont = document.createElement('DIV'); // create a div element
myCont.innerHTML = htmlStr; // create its children with the string
return myCont; // return the parent div
}
function getHTML(theNode)
{
var myCont = document.createElement('DIV');
myCont.insertBefore(theNode,null);
return myCont.innerHTML ;
}
The expression you need is:
str.match(/a href="([^"]*)"/)[1]
But this assumes there is only one a tag in your string and you used double quotes to delimit the href.
Made a jsfiddle: http://jsfiddle.net/eDAuv/
Why not extract the link BEFORE you store it in a string?
myLink = $(".myDiv a").html()
This could work:
var link = $(str).find("a").get(0).outerHTML;
alert(link);

Categories

Resources