How can set the title of all the links in a page - javascript

I would like to make some javascript code that once run adds a title of each link that is the title of the page it leads to. Sorry, all I can figure out is...
<body onload="replace()">
<script>
function replace() {
document.getElementsByTagName("a").title=this.href;
}
</script>
hi
hi2
hi3
</body>
But nothing happens and I can't figure it out.

more simple, just place correctly your script:
<body>
hi
hi2
hi3
<!-- Script for everything, just placed before </body>-->
<script>
document.querySelectorAll('a').forEach(A=>{ A.title = A.href })
</script>
</body>

getElementsByTagName returns a collection of elements, you need to use loop for setting whatever to each link.
<body onload="replace()">
<script>
function replace() {
// find all links
var links = document.getElementsByTagName("a");
// loop the collection and set title to each one
for (var i = 0; i < links.length; i++) {
links[i].title = links[i].href;
}
}
</script>
hi
hi2
hi3
</body>

Afaik, there is no way to detect a page title from a different page in JS. If you know the titles in advance, you can create a mapping object and loop over your links like so:
var map = [['link','title'],['link','title']];
$('a').each(function() {
for(var i=0; i<map.length; i++) {
if(map[i][0] == $(this).attr('src'))
$(this).attr('title', map[i][1]);
}
});
That should set all your links with the appropriate page titles based on matching the src attributes of each link against the link in your mapping object

You can use window.location.href instead of this.href. Also, you probably need to run through each link in the tag list:
function start() {
var links = document.getElementsByTagName("a");
for (var i = 0; i < links.length; i++) {
links[i].title = window.location.href;
}
}
window.load = start();
hi
hi2
hi3

Try this answer, I have tried to add comments so that you could understand what has happened:
<a class="link" href="about.html">About</a>
<a class="link" href="careers.html">Careers</a>
<a class="link" href="contact.html">Contact</a>
<script>
//create a true array
var links = Array.from(document.getElementsByTagName("a"));
window.addEventListener(
"load", //Trigger Load event of window object
()=> //return this function
{
//links is an array of a-tag objects
for (let i = 0; i < links.length; i++)
{
//for each a tag object
//set the attribute targeted below
links[i].setAttribute
(
//target the title attribute
"title",
//set it to the current href attribute value of the that a-tag object
links[i].getAttribute("href")
);
}
}
);
</script>

Related

How do I add target=“_blank” to a link within a div with an specific class name?

I´m trying to add target=“_blank” to all the links within the divs with an specific class name. I know how to do it with an ID:
window.onload = function(){
var anchors = document.getElementById('link_other').getElementsByTagName('a');
for (var i=0; i<anchors.length; i++){
anchors[i].setAttribute('target', '_blank');
}
}
But i´m trying to replicate the same, using classes instead of IDS. Any ideas of a how to do this without jquery?.
Thanks in davanced!
You can use querySelectorAll() and include a CSS selector. So if your class name is link-other:
document.querySelectorAll('.link-other a')
.forEach(function(elem) {
elem.setAttribute('target', '_blank');
})
<div class="link-other">
Wikipedia
Google
</div>
Use querySelectorAll and loop just like you did.
var anchors = document.querySelectorAll(".link_other a");
Or you can use getElementsByClassName and nested loops.
var parents = document.getElementsByClassName(".link_other");
for (var i = 0; i < parents.length; i++) {
var anchors = parents[i].getElementsByTagName("a");
for (var j = 0; j < anchors.length; j++) {
anchors[j].setAttribute('target', '_blank');
}
}
You can use document.querySelectorAll() which takes a css expression:
var anchors = document.querySelectorAll('.my_class a');
for (var i=0; i<anchors.length; i++){
anchors[i].setAttribute('target', '_blank');
}
Or (ab)using the array prototype:
[].forEach.call(document.querySelectorAll('.my_class a'), function(el) {
el.setAttribute('target', '_blank');
});
You should also consider using addEventListener instead of window.onload:
window.addEventListener('load', function() {
// ...
});
Or the more appropriate:
document.addEventListener('DOMContentLoaded', function() {
// ...
});
You can also use the old school <base> element which will can set defaults for all a tags:
var base_el = document.createElement('base');
base_el.setAttribute('target', '_blank');
document.head.appendChild(base_el);
To achieve your expected result use below option
var addList = document.querySelectorAll('.link_other a');
for(var i in addList){
addList[i].setAttribute('target', '_blank');
}
Codepen - http://codepen.io/nagasai/pen/QEEvPR
Hope it works

Get Attributes Value for multiple class

Im a Javascript beginner. I want to get attribute value on multiple class elements. I tried with IDs, but it's not revelent since IDs are supposed to be unique.
My HTML looks like this :
<a href="#" class="Test" onclick="myJavascriptFunc()" data="FooBar_1">
<a href="#" class="Test" onclick="myJavascriptFunc()" data="FooBar_2">
<a href="#" class="Test" onclick="myJavascriptFunc()" data="FooBar_3">
Any help would be appreciated.
Thanks
First close your anchor Tags
Test1
Test2
Test3
then use this javascript function
function myJavascriptFunc(item)
{
alert(item.getAttribute("data"));
return false
}
and let me know if it works
Trying using this:
function test(){
var x = document.getElementsByClassName("myClass");
var i;
for (i = 0; i < x.length; i++) {
var val = x[i].innerHTML; //innerHTML returns the written text inside the element tag
alert(val);
alert(x[i].getAttribute("data")); //this will give you the data attribute
}
}
You can get any other attribute you like from that element just by replacing the innerHTML by that attribute's name
I'm too late as always, but I would use the HTML 5 dataset attribute:
<!DOCTYPE html>
<html>
<head>
<script>
function doSomething(classname,func,datakey)
{
var hrefs = document.getElementsByClassName(classname), // get all elements with the class
i = 0; // initialize the loop
for(;i < hrefs.length; i++) // iterate through all elements
{
func(hrefs[i].dataset[datakey]); // execute the passed function with the content of the dataset as first argument
}
}
function alertval(value) // example function to do something with it
{
alert(value);
}
window.onload = function ()
{
doSomething("Test",alertval,"something"); // just test it
}
</script>
</head>
<body>
Test1
Test2
Test3
</body>
</html>
You are probably wondering why you can't just reach the data attribute using the this keyword from myJavascriptFunc(). That's because you are using inline event registration, and the this keyword then refers to the window object. To get around this you must make sure the this keyword is actually written into the onclick property.
var elems = document.getElementsByClassName('test');
for (var i = 0, len = elems.length; i < len; i++) {
elems[i].onclick = myJavascriptFunc;
}
function myJavascriptFunc() {
alert(this.getAttribute('data'));
}
<!DOCTYPE html>
<html>
<head>
</head>
<body>
FooBar_One<br>
FooBar_Two<br>
FooBar_Three
</body>
</html>
A way to see the difference:
<element onclick="myJavascriptFunc()">. // this refers to the window object as the element does not get passed along.
<element onclick="alert(this.getAttribute('data'));">. // this refers to the element.

javascript - get attribute value by text value

<a href='http://example.com'>Goes To Example.com</a>
I want to get the href value of this. This link will always be on the page
I will usually do something like: document.getElementsByTagName('a')[5]. However, the number of links are always changing so it isn't reliable at all. Is there a way I can get it by the text Goes To Example.com?
As you said in comment you can use jquery, use Contains like bellow
$('a:contains("Goes To Example.com")')
DEMO
Use the JQuery :contains() selector. You can then get the attribute "href", as follows:
$("a:contains(Goes To Example.com)").attr("href");
For example, the following snippet will popup an alert with http://example.com inside it:
<html>
<head>
<script src="https://code.jquery.com/jquery-1.11.1.min.js"></script>
</head>
<body>
<a href='http://example.com'>Goes To Example.com</a>
<script>
alert($("a:contains(Goes To Example.com)").attr("href"));
</script>
</body>
</html>
You could use xpath:
document.evaluate(
'/html/body//a[text()='Goes To Example.com']/#href',
document, null, XPathResult.ANY_TYPE, null);
You can iterate over the result (which is of type XPathResult) using iterateNext.
See xpath documentation for details: https://developer.mozilla.org/en-US/docs/Web/API/document.evaluate.
You can do document.getElementById and give the id to the a tag. To get the text you can use innerHTML function
Working Fiddle
HTML Markup
<a id="test" href='http://example.com'>Goes To Example.com</a>
JS:
document.getElementById("test").innerHTML
If you want it by href attribute only then you have to loop it over
var els = document.getElementsByTagName("a");
for (var i = 0, l = els.length; i < l; i++) {
var el = els[i];
if (el.href === 'http://www.example.com/') {
alert(el.innerHTML);
}
}
You can do it like this:
var links = document.getElementsByTagName('a');
var requiredId = "";
for(var i=0; i<links.length; i++){
if(links[i].innerHTML == "Goes To Example.com"){
requiredId = links[i].getAttribute('id');
}
}

Having issue in changing style through JavaScript

Hi i am trying to change Display property of any HTML Tag with certain attribute..
But after many tries i am unable to change the tag properties.. My code is as below
function getAllElementsWithAttribute(attribute)
{
var matchingElements = [];
var allElements = document.getElementsByTagName('*');
for (var i = 0; i < allElements.length; i++)
{
if (allElements[i].getAttribute(attribute))
{
// Element exists with attribute. Add to array.
matchingElements.push(allElements[i]);
}
}
return matchingElements;
}
tags = getAllElementsWithAttribute('data-shares');
for(i=0;i<tags.length;i++)
{
tags[i].style.display = "none";
}
And the HTML has below Tag
<div class="shareTools" data-shares="facebook" data-url="#" data-title="Facebook" data-description="Facebook">
<div class="shareToolsBox">
<ul class="shareToolsList">
<li data-share="facebook">
<span>Facebook</span>
</li>
</ul>
</div>
</div>
Does anyone has any idea how to change Tag Style of any tag which has attribut i-e data-shares...
Change the function call to:
tags = getAllElementsWithAttribute('data-shares');
Here's it working on a JS Bin demo: http://jsbin.com/ufogExo/1/ The <div>s with the data-shares attribute are all hidden.
The problem was indeed the extra commas you had on your function call arguments.
I believe this does what you want:
function getAllElementsWithAttribute(attribute)
{
var items = document.querySelectorAll('['+attribute+']'),
i = items.length;
while ( i-- > 0 && (items[i].style.display = 'none') );
}
getAllElementsWithAttribute('data-shares');
see
http://jsfiddle.net/754zR/

javascript unobtrusive

i have an html page, which is consist of many hyperlink like this inside body tag...
User Name
then i decide to use unobtrusive javascript ... then i'd like to change all the "a" tag to be...
<a id="354313" href=#>User Name</a>
when i click the second link above, i want that it'll call a function like the first link does,...
my question is how to get all the "a" element inside body tag then apply a function depend it's id...
With jQuery, something like this:
$('a').click(function() {
var id = this.getAttribute('id');
// Do something...
});
If you want it to work on all elements ever created, use this:
$('a').live('click', function() {
var id = this.getAttribute('id');
// Do something...
});
I hope this is what you are trying.
<script type='text/javascript'>
var alA = document.getElementsByTagName("a");
for(var aCounter=0;aCounter<alA.length;aCounter++) {
var singleA = alA[aCounter];
singleA.onclick = function () {
window.open = "http://www.example.com/?id="+singleA.id;
}
}
<script>
What you're after is this code:
<script type="text/javascript">
window.onload = function WindowLoad() {
var arrLinks = document.getElementsByTagName("a");
for (var i = 0; i < arrLinks.length; i++) {
var oLink = arrLinks[i];
var sCurHref = oLink.href;
if (sCurHref.indexOf("?id=") >= 0) {
var ID = sCurHref.split("?id=")[1];
if (ID.length > 0) {
oLink.id = ID;
oLink.href = "#";
oLink.onclick = function() {
document.location.href = sCurHref;
return false;
}
}
}
}
}
</script>
This will iterate all the links, changing the visible HREF to "#" and preserving their functionality, applying the proper ID. (Though you didn't say what's the use of that ID)
Feel free to mess around with the live test case: http://jsfiddle.net/yahavbr/uMbEY/
Something like:
<script language="javascript">
function myFunction(id)
{
alert(id);
}
</script>
<a id="354313" onclick="myFunction(this.id);" href="#">;User Name<;/a>
Not sure though Test it :)
I will rather say that add class to the links u want to handle this way
<a class="mylink" ... >User Name </a>
Now read the elements by class name. If you are using new browsers or any JS library like JQuery its great.
var links = document.getElementsByClassName("mylink") //Method in Mozilla Browser
Above are the links that you can process nicely without getting into trouble.
// Function that you want to call
function fake(id)
{
// Your content
}
// Get all "a" elements and put it in an Array
var links = window.document.getElementsByTagName("a");
for (var i=0; i<links.length; ++i)
{
fake(links[i].id);
}

Categories