Append data from div to link url - javascript

I am trying to have a div element on every page of my site that will contain the product number and then have a link that will put that number at the end.
For example,
<div id="productnumber">01101</div>
https://example.com/#
Then put the contents of the element with id "productnumber" after the # of the link.
Any idea if this is possible? Since this would make life easier than editing all existing pages and their respective php files.

Check for Element.innerHTML. You could use some inline JS and append it to the href-Attribute (which should be were id="purchaseurl" is now)

You can add a simple script to all your pages.
document.addEventListener("DOMContentLoaded", function() {
var productNumber = document.getElementById('productnumber').textContent;
Array.prototype.forEach.call(document.querySelectorAll('a[href~="purchaseurl"]'), function(link) {
// if you want to change the link
var currentHref = link.getAttribute('href');
link.setAttribute('href', currentHref + '#' + productNumber);
// if you want to change anchor text
var currentText = link.innerHTML;
link.innerHTML = currentText + productNumber;
});
});
<div id="productnumber">01101</div>
https://example.com/#

See getElementById, getElementsByTagName, and nextSibling.
var data = document.getElementById('productnumber'),
url = data.nextSibling.nextSibling;
url.innerText += data.innerText;
<div id="productnumber">01101</div>
https://example.com/#

Related

How to get text of element in a variable using jquery?

var markup = '<div class="ExternalClass34E9F553C2F74AA2B6D693A07BA166AC">Employee Self-Service pages have been corrected but may require you to refresh the page.</div><div class="ExternalClass34E9F553C2F74AA2B6D693A07BA166AC"> </div><div class="ExternalClass34E9F553C2F74AA2B6D693A07BA166AC">If the problem remains, follow these instructions.  </div>';
var str = "";
$(markup).find("div[class^='ExternalClass']").each(function(){
str += $(this).text();
})
How do I grab content of all the divs in the markup that starts with ExternalClass?
$(markup) selector contain all ExternalClass class and you can't use .find() because it doen't any matched child. You need to use .filter() to filter selected element.
var markup = "<div...";
var str = "";
$(markup).filter("div[class^='ExternalClass']").each(function(){
str += $(this).text();
})
var markup = '<div class="ExternalClass34E9F553C2F74AA2B6D693A07BA166AC">Employee Self-Service pages have been corrected but may require you to refresh the page.</div><div class="ExternalClass34E9F553C2F74AA2B6D693A07BA166AC"> </div><div class="ExternalClass34E9F553C2F74AA2B6D693A07BA166AC">If the problem remains, follow these instructions.  </div>';
$(markup).filter("div[class^='ExternalClass']").each(function(){
console.log($(this).text());
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
jQuerys .find() only loops through the children of the specific HTML you selected. Your variable markup has no children with the fitting class selector.
The easiest way I can imagine getting this solved, is to wrap all you have in markup inside another div, and then use your jQuery selector - that works:
var markup = '<div class="ExternalClass34E9F553C2F74AA2B6D693A07BA166AC">Employee Self-Service pages have been corrected but may require you to refresh the page.</div><div class="ExternalClass34E9F553C2F74AA2B6D693A07BA166AC"> </div><div class="ExternalClass34E9F553C2F74AA2B6D693A07BA166AC">If the problem remains, follow these instructions.  </div>';
markup = '<div>' + markup + '</div>';
var str = "";
$(markup).find("div[class^='ExternalClass']").each(function(){
str += $(this).text();
})

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

How to append an element to a div which is without id

I want to use javascript to add a link inside a div, this div doesn't have id , it does has a class though:
<div class="details">
<div class="filename">test.xml</div>
<div class="uploaded">25/12/2012</div>
Delete
<div class="compat-meta"></div>
</div>
How to add a link inside the "details" div and above the "delete" link?
The link I want to add is:
Edit
go for jquery, it's simple and clean.
you can grab any element with a particular class say
<div class="className" ></div>
like this
<script>
$('.className');
</script>
now you want to append someother element just before the anchor having delete class, well than you can do this:
$('.delete').before('Edit');
there are other methods also to append an element inside any other element or dom
1. $('.className').append('<div> i will be appended at the bottom of this element</div>');
2. $('.className').after('<div> i will be appended right after this element</div>');
for using jquery, you will need its api, directly use this link in your page or, download the latest jQuery api and use it.
its simpler and easier.
function hasClass(element, className) {
var s = ' ' + element.className + ' ';
return s.indexOf(' ' + className + ' ') !== -1;
}
/**
* from: http://www.dustindiaz.com/getelementsbyclass
*/
function $class(className, context, tag) {
var classElements = [],
context = context || document,
tag = tag || '*';
var els = context.getElementsByTagName(tag);
for (var i = 0, ele; ele = els[i]; i++) {
if (hasClass(ele, className)) {
classElements.push(ele);
}
}
return classElements;
}
then use the $class('delete') to locate the elements, and then prepend new elements
It's always best to search by id, it is most efficient. However if it comes to it, you may find elements by class or tag name as well.
I recommend using jQuery, and changing the existing tag you have:
$('a').attr('href', '#edit_link').text('Edit').removeClass('delete').addClass('edit');
If it is not possible to add an id to the element you're finding, find an element somewhere higher in the tree that has an id, and go from there:
$('#someHigherId > div > a')...
You could use jQuery:
$('div.details a.delete').before('Edit');
You can do it using javascript like this
<script type="text/javascript">
function addtext(what){
if (document.createTextNode){
var link = document.createElement('a');
link.setAttribute('href', '#edit_link');
link.setAttribute('id', 'edit');
link.setAttribute('class', 'edit');
document.getElementsByTagName("div")[0].appendChild(link)
document.getElementById("edit").innerHTML = what;
}
}
</script>
<div class="details" id="mydiv" onClick="addtext('Edit')">
<div class="filename">test.xml</div>
<div class="uploaded">25/12/2012</div>
Delete
<div class="compat-meta"></div>
</div>
Using pure JavaScript:
var div = document.getElementsByClassName('details')[0],
deleteLink = div.getElementsByClassName('delete')[0],
editLink = document.createElement('a');
editLink.textContent = 'Edit';
editLink.className = 'edit';
editLink.href = '#edit_link';
div.insertBefore(editLink, deleteLink);

How do I create a link using JavaScript?

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

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