To append:
_target="_blank"
To all links in an HTML page I use:
var links = document.querySelectorAll("a");
for (var i=0;i<links.length;i++) {
links[i].target="_blank";
}
But for some reason, when I use the exact same code and try to append:
onclick="alert(2)"
Like so:
var links = document.querySelectorAll("a");
for (var i=0;i<links.length;i++) {
links[i].onclick="alert(2)";
}
It does not work.
Can anyone show me how to do this? (preferably in javascript instead of jQuery)
thanks!
You can use your original query with a slight modification:
var links = document.querySelectorAll("a");
for (var i=0;i<links.length;i++) {
links[i].onclick=function() { alert(2) };
}
Try
links[i].onclick = function() { alert(2); };
As other answers show, the onclick property should contain a function. If you really want to assign a Javascript code string, you can do it with setAttribute.
var links = document.querySelectorAll("a");
for (var i = 0; i < links.length; i++) {
links[i].setAttribute('onclick', "alert(2)");
}
Link 1
Link 2
Link 3
Link 4
Related
This is my code:
var links = document.querySelectorAll ("a");
for (let i = 0; i <links.length; i++) {
links[i].setAttribute("target", "_self");
}
My goal, obviously, is to have all the links open on the current page, but only some of them become _self and the rest remain _blank, why?
I'm providing you 2 ways to achieve what you want :
First code is what you provided, and the second one is an other way to add _self attribute value on links.
let links = document.querySelectorAll ("a");
for (let i = 0; i <links.length; i++) { //1st way
links[i].setAttribute("target", "_self");
}
links.forEach(link => { //2nd way
link.target = "_self";
});
<body>
Youtube
Google
Twitter
Netflix
</body>
i'm completely new to Javascript and I wanted to create an Greasemonkey Script that replaced "/text/othertext/" to "/text2/text3" on all the href elements of the document. That's what i came up with, and as expected, it doesn't work:
var links = document.getElementsByTagName('a');
for (i=0; i<links.length; i++)
{
var gethref = links[i].getAttribute('href');
gethref = gethref.replace(/text\/othertext/g,'text2\/text3');
links[i].setAttribute("href", gethref);
}
Thanks in advance!
Edit: ok, i know why my script is not working, but i don't know if it can be fixed, i'm trying to replace elements that load after the page is completely loaded (maybe with ajax?)
http://i.imgur.com/7n5V7Bi.png
This code works. Your code looks okay too. Perhaps you are loading the script before the document elements? Note how my elements are listed before my script:
link
link
<script>
var links = document.getElementsByTagName('a');
for(var i = 0; i < links.length; i++) {
var href = links[i].getAttribute('href');
href = href.replace('before', '#');
links[i].setAttribute('href', href);
}
</script>
Edit, based on your comments a dirty fix to cause delay in your app before running a script is to use the setTimeout function. To delay five seconds for example, you might use it like this:
link
link
<script>
setTimeout(function() {
var links = document.getElementsByTagName('a');
for(var i = 0; i < links.length; i++) {
var href = links[i].getAttribute('href');
href = href.replace('before', '#');
links[i].setAttribute('href', href);
}
}, 5000); // < --- note the time in ms here
</script>
Not too sure why your code wouldn't be working.
I've put together the following snippet which might help.
(function() {
var anchors = document.querySelectorAll('a');
for(var i = 0; i < anchors.length; i++) {
var newHref = anchors[i].getAttribute('href').replace(/text\/othertext/g,'text2\/text3');
anchors[i].setAttribute('href', newHref);
}
}());
a {
display: block;
}
<!DOCTYPE html>
<head></head>
<body>
Some link
Some other link
</body>
If you run this snippet you'll see only one anchor is updated correctly as intended.
Hope that helps you out!
The easiest solution would be to wrap your code in this:
window.onload = function(){
/* your code here */
};
This will ensure that your code (especially if you've placed your script in the of the document, won't load until the whole page is loaded (including text, images, etc).
window.onload = function() {
document.body.innerHTML = document.body.innerHTML
.replace('<a href="text/othertext/"', '<a href="text2/text3"');
};
<!DOCTYPE html>
<head></head>
<body>
Some link
Some other link
</body>
I am looking for a way how to open few links in new tabs by one click.
Here is some HTML-code I wrote.
<ul>
<li>Google</li>
<li>Bing</li>
<li>Ebay</li>
<li>Amazon</li>
</ul>
<hr>
Open all links above by one click!
UPD: If it is possible, it would be great if it will search all links on a page wrapped with <li></li>, push them to array, and after a click link should open next 4 links from array.
jsFiddle example
Without questioning your motives (because you will be blocked by the popup blocker),
function open4links () {
var links = ['http://...', 'http://...', 'http://...', 'http://...'];
for (var i = 0; i < links.length; i++) {
window.open(links[i], '_blank');
}
}
(the a element).onclick = open4links;
Here, this works for me (based on the updated request): http://jsfiddle.net/R7qFv/4/
This keeps track of which links have been opened, so each time you click the link, it will open the next 4 in the list.
$("#openlinks").on("click", (function(){
var count = 0, nAtOnce = 4, $links = $("li a");
var openLinks = function(){
for (var i = 0; i < nAtOnce && count < $links.length; i++) {
window.open($links.eq(count++).attr("href"), '_blank');
}
};
return openLinks;
})());
I wrote it using jQuery because it's easier for me, but I'm sure you can translate if needed.
using window.open:
$('a').click(function(e) {
e.preventDefault();
$('li a').each(function(){
window.open($(this).attr("href"), '_blank');
});
});
As you can see in the JsFiddle, most browsers won't accept this because it is considered spam.
Use this to find all links in your html code and open in other window
<script type="text/javascript">
function OpenLinks(){
var arr = [];
$("#list a").each(function(){
arr.push(jQuery(this).attr("href"));
});
for(var i =0; i < arr.length;i++){
window.open(arr[i]);
}
}
</script>
obs: use jquery!
I want to make a script that disables hyperlinks and instead fires a function when one is clicked.
should work as
<a onclick="talk('http://google.com)'></a>
Is there a way to know when the wants to redirect and instead run "talk()" or display an alert window?
var anchors = document.getElementsByTagName('a');
for (var a = 0; a < anchors.length; a++){
anchors[a].href = "javascript:talk('" + anchors[a].href + "');";
}
Use some discretion though...
This solution uses (DOM Level 0) event handling instead of touching the href directly.
(function () {
var anchors = document.getElementsByTagName('a'),
i = anchors.length;
while (i--) {
anchors[i].onclick = function () {
talk(this.href);
return false;
};
}
}());
Edit: The benefit of this approach is it's much simpler to put the href back when you want to. Given an anchor tAnchor, you merely need to unset the onclick attribute:
tAnchor.onclick = null
In javascript I have a reference to a div. In that div is an anchor element with a name='foundItem'
How do I get a reference to the anchor with the name foundItem which is in the Div I have the reference of?
There are 'many' foundItem anchors in other divs on the page. I need 'this' DIVs one.
// assuming you're not using jquery or mootools
// assume div is mydiv
var lst = mydiv.getElementsByTagName('a');
var myanchor;
for(var i=0; i<lst.length; ++i) {
if(lst[i].name && lst[i].name == 'foundItem') {
myanchor = lst[i];
break;
}
}
// the mootools method
var myanchor = $(mydiv).getElement('a[name=foundItem]');
You can use the getElementsByTagName method to get the anchor elements in the div, then look for the one with the correct name attribute:
var found = null;
var e = divReference.getElementsByTagName('A');
for (var i=0; i < e.length; i++) {
if (e[i].name && e[i].name == 'foundItem') {
found = e[i];
break;
}
}
If found is not null, you got the element.
If you happen to use the jQuery library, you can let it do the searching:
var found = null;
var e = $(divReference).find('a[name=foundItem]');
if (e.length == 1) found = e.get(0);
Use a JavaScript library like jQuery and save yourself time.
var theAnchor = $('#divId a[name=foundItem]');
Using jquery, it's dead easy:
<script type="text/javascript">
$(function(){
var item = $("#yourDivId a[name=foundItem]")
)};
</script>
Update:
As per the comments, if you have control over what to id/name/class your anchor tag/s, it would be best to apply a class to them:
<div id="firstDiv">
test
</div>
<div id="secondDiv">
test another one
</div>
<!-- and so forth -->
<script type="text/javascript">
$(function(){
var item = $("#firstDiv a.foundItem");
alert(item.html()); // Will result in "test"
var item2 = $("#secondDiv a.foundItem");
alert(item2.html()); // Will show "test another one"
)};
</script>
If you're doing anything with javascript, jQuery saves you tons of time and is worth investing the effort to learn well. Start with http://api.jquery.com/browser/ to get an intro to what's possible.
Not sure if this helps, but wanted a function to handle the load of a page dynamically and scroll to the anchor of choice.
function scrollToAnchor(anchor_val) {
alert("" + anchor_val);
var page = document.getElementById('tables');
var found = null;
var cnt = 0;
var e = document.getElementsByTagName('a');
for (var i = 0; i < e.length; i++) {
if (e[i].name && e[i].name == anchor_val) {
found = e[i];
break;
}
cnt++;
}
if (found) {
var nPos = found.offsetTop;
alert("" + nPos);
page.scrollBy(0, nPos);
} else {
alert('Failed with call of scrollToAnchor()' + cnt);
}
}