I hope somebody can help me... I try to grab a parameter, which is saved in the head of a html-site, and add this parameter to all links on the site, which have no "rel='gallery'"-attribut. some links have allready other GET-parameters. It looks like this:
<head>
<script type="text/javascript">
var ParameterNew = "test";
</script>
</head>
[...]
Search: Google<br/>
Social Media: Facebook
<br/><br/>
<a rel="gallery" href="img/1.jpg">Gallery Link 1</a><br/>
<a rel="gallery" href="img/2.jpg">Gallery Link 2</a><br/>
So I try to append the ParameterNew behind all links, which have no rel-attribut.
At the end it has to looks lie this:
<head>
<script type="text/javascript">
var ParameterNew = "test";
</script>
</head>
[...]
Search: Google<br/>
Social Media: Facebook
<br/><br/>
<a rel="gallery" href="img/1.jpg">Gallery Link 1</a><br/>
<a rel="gallery" href="img/2.jpg">Gallery Link 2</a><br/>
I wrote this one. It only replace the innerHTML (such as an example):
var links = document.getElementsByTagName("a");
for (var i = 0; i < links.length; i++) {
if (links[i].target !== "_blank")
links[i].innerHTML = 'test';
}
I only have problem to append the parameter... Maybe someone can help? thanx
This is a reasonably simple solution that takes into account your exact example conditions. That is, it assumes you have simple links so that all that needs to be done is check which connector to use in adding the parameter. If your links can contain parameters that are links, you'll need to do something more complex to figure out whether to use a ? or & to append the parameter.
var links = document.getElementsByTagName("a");
for (var i = 0; i < links.length; i++) {
if (links[i].rel != 'gallery') {
var href = links[i].href,
connector = '?';
if (href && href.match(/\?/)) {
connector = '&';
}
links[i].href = href + connector + 'parameter=' + ParameterNew;
}
}
Related
I have a page with a download button like this:
<a href="http://www.example.nl/filename.pdf" download>DOWNLOAD</a>
Below, I want (text) to automatically display "filename.pdf" (rather than having to do this by hand hundreds of times).
I found the script below that displays the filename of the PAGE but I want it to display the FILENAME of a HREF I've used on the actual page.
Any help is much appreciated.
<script type="text/javascript">
var segment_str = window.location.pathname;
var segment_array = segment_str.split( '/' );
var last_segment = segment_array.pop();
document.write(last_segment);
</script>
Thanks in advance!
Not sure where you want the "text" to display... so I put it in a div
<a href="http://www.example.nl/filename.pdf" download>DOWNLOAD</a>
<div id="result">
</div>
The big change, is to get all the "a" tags, using getElementsByTagName... and then iterating over the list, and then you can use the string split, and pop off the last segment before appending it to a destination.
var input = document.getElementsByTagName('a');
for(i = 0;i < input.length; i++)
{
var segment_str = input[i].href;
var segment_array = segment_str.split( '/' );
var last_segment = segment_array.pop();
document.getElementById("result").innerText += last_segment;
}
Maybe this will help.
<div id=download1></div>
<script>
var filename = 'example.pdf';
$('#download1').html('' + filename + '');
</script>
New to Javascript. How can I search a page for text in a certain "p class" and click on the href link next to it? Trying to create a Chrome extension that will open a Twitter link in a new tab. I have a basic extension but stuck here. Any help is greatly appreciated.
How would I find the first href that mentions the Patriots (or any keyword) from a tweet?
HTML of a tweet:
<p class="js-tweet-text tweet-text">
'No chance' Patriots franchise tag Aqib Talib
<a href="http://t.co/6dV3EHg5WU" rel="nofollow" dir="ltr" data-expanded-url="http://dlvr.it/4tsL8d" class="twitter-timeline-link" target="_blank" title="http://dlvr.it/4tsL8d">
<span class="tco-ellipsis"></span>
<span class="invisible">http://</span>
<span class="js-display-url">dlvr.it/4tsL8d</span>
<span class="invisible"></span>
<span class="tco-ellipsis">_</span>
</span></a></p>
You can use querySelectorAll() to find the items to search, do the search in the content yourself and then follow the DOM to get the href from the next link:
function findTextAndClick(findText) {
var items = document.querySelectorAll(".tweet-text");
for (var i = 0; i < items.length; i++) {
var text = items[i].textContent || items[i].innerText;
if (text.indexOf(findText) >= 0) {
var links = items[i].querySelectorAll("a");
if (links.length) {
window.location = links[0].href;
return;
}
}
}
}
Sample usage on your HTML:
findTextAndClick("Patriots");
I'm trying to create a script that will make it easier for users to use a custom button and I have something like
<script src="http://host.com/file.js?id=12345"></script>
What I wonder is how can I, in the file.js get that id parameter.
if I use document, it will get the original html page that has the script line and what I need is that id.
is there any way i can get that id successfully? What should be the scope?
added
the idea is that I can have several buttons in the page for example to have a small and simply list:
<ul>
<li><script src="http://host.com/file.js?id=12345"></script></li>
<li><script src="http://host.com/file.js?id=23456"></script></li>
<li><script src="http://host.com/file.js?id=34567"></script></li>
</ul>
this will ultimately translate to
<ul>
<li><a class="view40btn" href="#" data-id="12345"><strong>V40</strong> Watch the video</a></li>
<li><a class="view40btn" href="#" data-id="23456"><strong>V40</strong> Watch the video</a></li>
<li><a class="view40btn" href="#" data-id="34567"><strong>V40</strong> Watch the video</a></li>
</ul>
the list above will look like this in HTML:
My only issue is that I can't assign the correct id to the data-id attribute as this is generated in the file.js.
result
from Paulpro answer I got it working with his idea and knowing that the client will have much more scripts loaded and several with id's I changed it a bit for the final and working version:
var id = (function(){
var scripts = document.getElementsByTagName('script');
for(var i = 0, result = {}; i < scripts.length; i++)
if(scripts[i].hasAttribute('data-viewfileid'))
result['id'] = decodeURIComponent(scripts[i].getAttribute('data-viewfileid'));
return result['id'];
})();
var html = '<a class="view40btn" href="#" data-id="' + id + '"><strong>V40</strong> Watch the video</a>';
document.write(html);
the script for the user would only be:
<script data-viewfileid="4444" src="file.js" type="text/javascript"></script>
You can get the last script element on the page (which will always be the currently executing one):
var scripts = document.getElementsByTagName('script');
var s = scripts[scripts.length - 1];
Then modify one of the query string parsers from this question to work with that scripts src property:
var url = s.src;
var qs = url.substring(url.indexOf('?') + 1).split('&');
for(var i = 0, result = {}; i < qs.length; i++){
qs[i] = qs[i].split('=');
result[qs[i][0]] = decodeURIComponent(qs[i][2]);
}
That will give you an object containing all the query string properties on the current script. You can just access the properties like:
result['id']; // '12345'
In summary
To get the id parameter from within file.js, add the following code to the top of file.js:
var id = (function(){
var scripts = document.getElementsByTagName('script');
var s = scripts[scripts.length - 1];
var qs = s.src.substring(s.src.indexOf('?') + 1).split('&');
for(var i = 0, result = {}; i < qs.length; i++){
qs[i] = qs[i].split('=');
result[qs[i][0]] = decodeURIComponent(qs[i][3]);
}
return result['id'];
})();
Make sure it is not in any callback functions like a DOMReady callback.
Edit: You can probably reduce your script to:
var scripts = document.getElementsByTagName('script');
var id = scripts[scripts.length - 1].getAttribute('data-viewfileid');
var html = '<a class="view40btn" href="#" data-id="' + id + '"><strong>V40</strong> Watch the video</a>';
document.write(html);
JavaScript doesn't know anything about the script tag that loaded it. However, there are a few workarounds.
If the file is being preprocessed on the server, you could make the server render the value in the response:
(function() {
var id = <%= params.id %>;
//other stuff here
}());
Or you could give the script tag an id, and make your code find it and pull out the URL.
HTML:
<script src="http://host.com/file.js?id=12345" id="myscript"></script>
JS:
var id = document.getElementById('myscript').split('id=')[1];
Or in modern browsers you could perhaps do something like this to find script tags that match where you know the script is.
var scriptTag = document.querySelector('script[src^="http://host.com/file.js"]');
var id = scriptTag.src.split('id=')[1];
One more solution is to parse .js files with php interpreter. For example in apache configuration:
AddType application/x-httpd-php .js
And in JS:
alert('<?=$_GET["id"]?>');
You can put an ID on anything, including a script tag. So you can do something like this:
HTML:
<script id="myScript" src="http://host.com/file.js?id=12345"></script>
JS:
document.getElementById('myScript').src.split('=')[1]; to get the ID from that particular example string.
If that query string represents a timestamp (in which case you need the latest version) you can modify the JavaScript code to fetch the latest <script> tag like so:
var scripts = document.getElementsByTag('script');
var latestScriptId = scripts[scripts.length-1].src.split('=')[1];
EDIT: In the context of your new edit, you would then take latestScriptId and assign it to the data.id attribute corresponding to the button you would like to create...though again, semantically, it would just make more sense to use HTML's given id attribute, and additionally, since you are not using the href property for the anchor <a> tag, you're better off using a <button> element. So something like this would suffice:
var myButton = document.createElement('button');
myButton.className += 'view40btn';
myButton.id = latestScriptId;
According to your clarifications, what you asking how to do is not what you want to do.
Instead, include one script, and have multiple placeholder nodes.
HTML:
<ul>
<li class="mybutton" data-id="12345"></li>
<li class="mybutton" data-id="23456"></li>
<li class="mybutton" data-id="34567"></li>
</ul>
<script src="myscript.js"></script>
JS:
// myscript.js
var buttons = document.getElementsByClassName('mybutton');
for (var i = 0; i < buttons.length; i++) {
var button = buttons[i];
button.innerHTML = "my button html template here with id: "+ button.dataset.id;
}
See it work here: http://jsfiddle.net/zAdnB/
Javascript code does not "realise", that it is a part of some file. JS file is not "executable", there is no main method, which should be run after loading the file. You can not pass GET parameters to it - it is not clear how they should be interpreted.
In your HTML page, you should listen to "onload" method and then call the function from your file with your parameter.
I'm trying to replace every instance of "Administrator" on my page with "Admin" Or something similar to that. How would I replace that? If it helps, the span is inside an tag that has the class "user-title".
Like this page but I kinda need to be fed the answer. This is my first time working with javascript.
<ul class="author-ident">
<li class="username">
<a title="Go to Different55's profile" href="http://fwin.co.cc/pun/profile.php?id=2">Different55</a>
</li>
<li class="usertitle">
<span>Administrator</span>
</li>
<li class="userstatus">
<span>Online</span>
</li>
</ul>
I work mostly with JQuery so I can only give you a JQuery solution of the top of my head. Sorry if this is not an option for you. With JQuery you could do this...
$(".user-title").each(function(index){
$(this).html($(this).html().replace("Administrator", "Admin"));
});
NOTE: If you expect more than one instance of "Administrator" per span tag then you will need to do a regex replace like follows...
.replace(/Administrator/g, "Admin");
See this for more info on the regex flag (e.g. "g" means global - more than one)
EDIT: Here is a javascript version....
var spans = document.getElementsByClassName("user-title");
for (var i = 0; i < spans.length; i++)
{
spans[i].innerHTML = spans[i].innerHTML.replace(/Administrator/g, "Admin");
}
ANSWER: This is based on your provided sample HTML (note that I have changed the class name "usertitle" based on your html, check if this is correct)...
var parents = document.getElementsByClassName("usertitle");
for (var i = 0; i < parents.length; i++)
{
var spans = parents[i].getElementsByTagName("span");
for(var j = 0; j < spans.length; j++){
spans[j].innerHTML = spans[j].innerHTML.replace(/Administrator/g, "Admin");
}
}
The JQuery equivalent...
$(".usertitle span").each(function(index){
$(this).html($(this).html().replace("Administrator", "Admin"));
});
<script type="text/javascript">
function changeText(){
document.getElementById('anId').innerHTML = 'my friend';
}
</script>
<p>Welcome to the site <b id='anId'>dude</b> </p>
<input type='button' onclick='changeText()' value='Change Text'/>
This will change the content of that .
You can run JS that will look in every span and, if you find "administrator", that you can be use that snippet of code.
To do the replacement you mentioned (replacing all occurrences of Administrator with Admin inside all spans inside .user-title, use:
$('.user-title span').each(function() {
$(this).html($(this).html().replace(/Administrator/g, 'Admin'));
});
NOTE: Assuming you are using jQuery in your app
You can use this function :
function correct() {
var a = document.getElementsByClassName("user-title");
var i = 0;
for(i=0; i<a.length; i++) {
while((a[i].innerHTML).indexOf("Administrator") >= 0){
a[i].innerHTML = a[i].innerHTML.replace(/Administrator/g, 'Admin');
}
}
}
this function will get collection of all elements having class name as "user-title". then the n in for loop, we will access each element in collection, see if it's innerHTML has the word that you want to replace and if it has, we replace it.
Put all instances of the word "Administrator" into a <span> with a certain class, f.i.:
<span class="user_type">Administrator</span>
Then you can use jQuery to do:
$("span.user_type").html("Admin");
Note that this may not be the nicest thing to do but we don't have any other details on what you're trying to accomplish.
how could I arrange the following div's by the value in the attribute amount with jquery? Thanks.
<a href="#" id="id1" class="lTest" amount="12">
<div>abcd1</div>
<a/>
<a href="#" id="id2" class="lTest" amount="64">
<div>abcd2</div>
<a/>
<a href="#" id="id3" class="lTest" amount="32">
<div>abcd3</div>
<a/>
<a href="#" id="id4" class="lTest" amount="8">
<div>abcd4</div>
<a/>
This one should work.
<!doctype html>
<html>
<head>
<script src='jquery.js'></script>
<script>
$(document).ready(init);
function init() {
var parent = $('#someid');
var children = $('a', parent);
children.sort(function(a, b) {
return parseInt($(a).attr('amount')) - parseInt($(b).attr('amount'));
})
$.each(children, function(i, child) {
parent.append(child);
});
}
</script>
</head>
<body>
<div id="someid">
<div>abcd2</div>
<div>abcd4</div>
<div>abcd3</div>
<div>abcd1</div>
</div>
</body>
</html>
[Edit] Replaced by a SSCCE to prove it's working. I've changed x in abcdx to the expected ordering. You should end up with abcd1, abcd2, abcd3 and abcd4 in this order.
Try this:
var links = $('a.lTest').sort( function(a,b) { return $(a).attr('amount') - $(b).attr('amount'); } );
for ( var i = 1; i < links.length; i++ ) {
links.eq(i-1).insertBefore( links.eq(i) );
}
first, assume the tags are surrounded by a div (id ="testDiv")
Sorry, my initial way of doing this is wrong...
DO NOT DO THIS: BROKEN!!! (See edit below)
var testDiv = $('#testDiv');
var children = testDiv.children('.lTest');
children.each(function() {$(this).remove();});
var testArray = $.makeArray(children);
testArray.sort(function(a,b){
return parseInt($(a).attr('amount')) - parseInt($(b).attr('amount');
});
children.each(function() {testDiv.append(this);});
EDIT: THIS IS WORKING VERSION:
var testDiv = $('#testDiv');
var children = testDiv.children('.lTest').remove();
children = children.sort(function(a,b){
return parseInt($(a).attr('amount')) - parseInt($(b).attr('amount'));
});
testDiv.append(children);
Your first comment on Tinister's answer indicates that your test page doesn't know anything about JQuery. Make sure you are properly including JQuery in your tests and that the HTML is correctly constructed. Then you will probably find that one of the other answers works.
John