print the first link in the document - javascript

I would like to print the first link in the page with JavaScript. But when I use the following code, it doesn't work:
<html>
<head><title></title></head>
<body>
<a id="mylink" href="http://google.com">Google</a><br />
<script>
a=$('mylink').href;
document.write(document.links[0]);
</script>
</body>
</html>
Then I commented out the code "a=$('mylink').href", it suddenly worked, why? How come the varable a has any influence on the next statement?
Any answers are appreciated.

There's a few possibilities:
The object $ is not defined and caused a JavaScript error preventing your 2nd statement to execute
The $ object does not know what to do with the string passed in and errors
The returned value from $ does not have a value (ie - it returns undefined) which wont have a property href, causing a JavaScript error

the code is not working because in your example the $ object does not exist and will cause an error. It seems that you were trying to use a JavaScript framework like jQuery ($ object) but you forgot to include it.
Try to add the following script-Tag:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
If you wanted to use jQuery, you should also access attributes via the .attr("attrname") function. E.g.
var a = $('#mylink').attr('href');
Again if you wanted to use jQuery, you have to alter the selector from "mylink" to "#mylink" to specify that you were searching for the element with the id "mylink".

I am a bit confused as to what you are trying to do, but couldn't you just write the whole link in js? Ex:
<script>
<!--
document.write('Google');
-->
</script>
<noscript>
Google
</noscript>
The comment tag in the script is ignored and is only there so browsers that don't support javacript won't print it in the document. The <noscript> is so browsers that don't support javascript have alternate content.

It doesn't work because a=$('mylink').href fails to execute and stop executing of following code. The code document.write(document.links[0]) is correct. When you call it without previous wrong line, it just works.
I think in the first line you're trying to use jQuery library. If you want to do it, you need to include jQuery library using <script> tag, then use the following code:
document.write($('a:first').attr("href"));

Just remove the jQuery stuff, you don't need it. As you've already discovered, there is a document.links collection so if you want to print the herf value of the first link in the document:
document.write(document.links[0].href)
and you're done.

Related

Why can't I use a <script> tag for jQuery anywhere?

This is an issue of scope I believe. I wish to use jQuery in a Joomla module and include the code within a tags in the php source. This works:
<script> alert("foo"); </script>
but this doesn't:
<script> alert($.jquery); alert(jQuery.jquery); </script>
which should produce at least 1 alert box with the jQuery version, but the alert says "undefined". The webpage <head> section already includes jQuery, and it is used in the html stream before the above <script>. I don't believe the <script> block defines a new, independent script scope / context, but that is how it behaves.
Add .fn.:
alert(jQuery.fn.jquery);
// or
alert($.fn.jquery);
Or try using jQuery as a function:
alert(jQuery().jquery);
// or short:
alert($().jquery);
Michael pointed out another one:
alert(jQuery.prototype.jquery);
// so we can also add
alert($.prototype.jquery);
If you want your code to work:
// add somewhere before:
jQuery.extend(jQuery, {jquery: jQuery.fn.jquery});
// Than this should work just fine:
alert(jQuery.jquery);
alert($.jquery);
Extend JQuery object ($ or jQuery) by .jquery equal to jQuery.fn.jquery.
As you can see we can add any properity to jQuery. Let's do jQuery.version:
$.extend($,{version:$().jquery});
If you want version you need
jQuery.fn.jquery
You can do
jQuery.fn.jquery
You can also do
jQuery.prototype.jquery

Getting started with jQuery -- hiding an element

Have you noticed that every 10 questions on this site is about jQuery?
Anyway...
I'm using jQuery for the first time. I don't know if I loaded it correctly. When I run this code:
<script type="text/javascript">
function allDayClicked() {
if (jQuery) alert("loaded");
var allday = document.getElementById("allDayEvent");
var start = document.getElementById("<%=startTimeSelector.ClientID%>");
$('allDayEvent').hide();
}
</script>
The alert appears, saying "loaded", but nothing else happens; the html checkbox doesn't go invisible. I get no kind of error in my javascript output.
Is it possible I haven't successfully loaded jQuery? I added a reference to it in my visual studio project and generated this by dragging it to default.aspx:
<script src="Scripts/jquery-1.6.1.min.js" type="text/javascript"></script>
Otherwise, what's going on?
jQuery takes a css selector, not an id. If you want an id use the css form of declaring an id.
$('#allDayEvent').hide();
jQuery is loaded fine, you're just using it incorrectly. You should be doing either:
$('#allDayEvent') // recommended, the '#' means ID
Or:
$(allday) // since you already grabbed it with getElementById
jQuery can take a lot of different objects with $(). The options are listed here.
You are missing the # in your ID selector.
Change $('allDayEvent').hide();
to
$('#allDayEvent').hide();
Assuming that your checkbox has an id "allDayEvent", you just need the hash (#) in this line:
$('#allDayEvent').hide();

How do I get the original innerHTML source without the Javascript generated contents?

Is it possible to get in some way the original HTML source without the changes made by the processed Javascript? For example, if I do:
<div id="test">
<script type="text/javascript">document.write("hello");</script>
</div>
If I do:
alert(document.getElementById('test').innerHTML);
it shows:
<script type="text/javascript">document.write("hello");</script>hello
In simple terms, I would like the alert to show only:
<script type="text/javascript">document.write("hello");</script>
without the final hello (the result of the processed script).
I don't think there's a simple solution to just "grab original source" as it'll have to be something that's supplied by the browser. But, if you are only interested in doing this for a section of the page, then I have a workaround for you.
You can wrap the section of interest inside a "frozen" script:
<script id="frozen" type="text/x-frozen-html">
The type attribute I just made up, but it will force the browser to ignore everything inside it. You then add another script tag (proper javascript this time) immediately after this one - the "thawing" script. This thawing script will get the frozen script by ID, grab the text inside it, and do a document.write to add the actual contents to the page. Whenever you need the original source, it's still captured as text inside the frozen script.
And there you have it. The downside is that I wouldn't use this for the whole page... (SEO, syntax highlighting, performance...) but it's quite acceptable if you have a special requirement on part of a page.
Edit: Here is some sample code. Also, as #FlashXSFX correctly pointed out, any script tags within the frozen script will need to be escaped. So in this simple example, I'll make up a <x-script> tag for this purpose.
<script id="frozen" type="text/x-frozen-html">
<div id="test">
<x-script type="text/javascript">document.write("hello");</x-script>
</div>
</script>
<script type="text/javascript">
// Grab contents of frozen script and replace `x-script` with `script`
function getSource() {
return document.getElementById("frozen")
.innerHTML.replace(/x-script/gi, "script");
}
// Write it to the document so it actually executes
document.write(getSource());
</script>
Now whenever you need the source:
alert(getSource());
See the demo: http://jsbin.com/uyica3/edit
A simple way is to fetch it form the server again. It will be in the cache most probably. Here is my solution using jQuery.get(). It takes the original uri of the page and loads the data with an ajax call:
$.get(document.location.href, function(data,status,jq) {console.log(data);})
This will print the original code without any javascript. It does not do any error handling!
If don't want to use jQuery to fetch the source, consult the answer to this question: How to make an ajax call without jquery?
Could you send an Ajax request to the same page you're currently on and use the result as your original HTML? This is foolproof given the right conditions, since you are literally getting the original HTML document. However, this won't work if the page changes on every request (with dynamic content), or if, for whatever reason, you cannot make a request to that specific page.
Brute force approach
var orig = document.getElementById("test").innerHTML;
alert(orig.replace(/<\/script>[.\n\r]*.*/i,"</script>"));
EDIT:
This could be better
var orig = document.getElementById("test").innerHTML + "<<>>";
alert(orig.replace( /<\/script>[^(<<>>)]+<<>>/i, "<\/script>"));
If you override document.write to add some identifiers at the beginning and end of everything written to the document by the script, you will be able to remove those writes with a regular expression.
Here's what I came up with:
<script type="text/javascript" language="javascript">
var docWrite = document.write;
document.write = myDocWrite;
function myDocWrite(wrt) {
docWrite.apply(document, ['<!--docwrite-->' + wrt + '<!--/docwrite-->']);
}
</script>
Added your example somewhere in the page after the initial script:
<div id="test">
<script type="text/javascript"> document.write("hello");</script>
</div>
Then I used this to alert what was inside:
var regEx = /<!--docwrite-->(.*?)<!--\/docwrite-->/gm;
alert(document.getElementById('test').innerHTML.replace(regEx, ''));
If you want the pristine document, you'll need to fetch it again. There's no way around that. If it weren't for the document.write() (or similar code that would run during the load process) you could load the original document's innerHTML into memory on load/domready, before you modify it.
I can't think of a solution that would work the way you're asking. The only code that Javascript has access to is via the DOM, which only contains the result after the page has been processed.
The closest I can think of to achieve what you want is to use Ajax to download a fresh copy of the raw HTML for your page into a Javascript string, at which point since it's a string you can do whatever you like with it, including displaying it in an alert box.
A tricky way is using <style> tag for template. So that you do not need rename x-script any more.
console.log(document.getElementById('test').innerHTML);
<style id="test" type="text/html+template">
<script type="text/javascript">document.write("hello");</script>
</style>
But I do not like this ugly solution.
I think you want to traverse the DOM nodes:
var childNodes = document.getElementById('test').childNodes, i, output = [];
for (i = 0; i < childNodes.length; i++)
if (childNodes[i].nodeName == "SCRIPT")
output.push(childNodes[i].innerHTML);
return output.join('');

Can't append HTML code into one div by using jQuery

I have one div id=userinfo
<html>
<head></head>
<body>
<div id=userinfo></div>
</body>
</html>
And now I want to append something into this div, depending on the localStorage.
if (localStorage==0){$("#userinfo").append("<p>Test</p>");} else {$("#userinfo").append("<p>Hello</p>");}
But it failed, no matter I input this script into separate JS file or add them into the head of the html file.
I tried exclude this with Google chrome developer tool's console, it works as expected.
I've tried another way round change the script into:
if (localStorage==0){alert("Test");} else {alert("Hello");}
And add this into JS file, it works!
So, now I'm stacked why my jQuery code not work?
The jquery append function takes an object as parameter and not a string html.
So this should solve your problem, $("#userinfo").append($('<p>Test</p>'))
You might have conflicts with other javascript libraries. Try to check out http://docs.jquery.com/Using_jQuery_with_Other_Libraries
Using jquery we can do like this below
$( "<p>Test</p>" ).appendTo( "#userinfo" );

Calling VBScript from Javascript

I've seen the related post on this, but it only covers using inline VBScript for onmouseover events, while calling a Javascript Function for the onClick.
Is there a way to call a VBScript Sub for the onClick event from a button that uses Javascript onmouseover and onmouseout events?
Currently when I try I get an error that the object does not support the property or method.
It is possible, but you will need to prefix all your script calls in HTML with the appropriate language.
onmouseover="javascript: vbfunction();"
If there are script calls that are not prefixed, you may get errors on the page as the parser doesn't know what scripting language is being used.
Put your code in the Head Tags: <head> </head>
Add your VBScript between these brackets:
<script type="text/vbscript">
</script>
Function myVBFunction()
' here comes your vbscript code
End Function
// From a hardcoded link, don't write a semicolon a the end:
link
You can read more about it here.
Make sure that the name of the sub you're calling doesn't match the ID of any other object in the script.

Categories

Resources