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" );
Related
Good day! Newbie here. I just want to know if it's possible to change the whole content of an html using javascript? I got some codes here. (not mine but whoever did this, thank you so much!) I don't know where to put/insert all the codes of the new layout like when you click a button then the whole content will change. Thank you very much for helping me.
<script language="Javascript">
<!--
var newContent='<html><head><script language="Javascript">function Hi()</script></head><body onload="Hi();"><p id="p">hello</p></body></html>';
function ReplaceContent(NC) {
document.write(NC);
document.close();
}
function Hi() {
ReplaceContent(newContent);
}
-->
</script>
The easiest way to do this is with jQuery.
function insertHtml()
{
var newHtml = '<div><span>Hello World</span></div>';
$('body').html(newHtml);
}
Something like that will replace the entire contents of body with newHtml. You can also do this with pure javascript using the .innerHtml property but jQuery has many advantages.
EDIT: If you want to add something to the DOM rather than replacing the entire thing, use
$('body').append(newHtml)
instead. This will add the content to the end of the body. This is very often used for things like adding rows to a table.
Yes it is possible but this code is not valid unless you remove the comment tags however don't use the document.write() after page load unless you want to overwrite everything in page including the script
I'm trying with Javascript code prettifier, and come up with a question.
If I do not assign class="prettyprint" to <pre> in static html, but wish to apply prettyprint later(e.g, when user click on a "colorize" button on my webpage), how can I achieve this?
Slightly modifying original run_prettify.js or prettify.js is acceptable, because I'm going to put this to offline use.
My experiment:
Writing try-delay-class.html:
<html>
<head>
<script src="https://google-code-prettify.googlecode.com/svn/loader/run_prettify.js"></script>
</head>
See it:
<pre>
class Voila {
public:
// Voila
static const string VOILA = "Voila";
// will not interfere with embedded tags.
}
</pre>
</html>
Open in Chrome v26, bring up the console, execute:
pres=document.getElementsByTagName('pre')
pres[0].className+=" prettyprint"
Syntax color does not come up.
According to a comment found here, How to get prettyprint to work on dynamically generated dom element , I find the way out. Just call:
PR.prettyPrint()
BTW: If you want to remove code color highlight, you cannot simply set pre's class to empty followed by PR.prettyPrint() again. PR.prettyPrint() can only attach color tags but not remove them. A feasible way to do that is saving your original <pre> content before applying prettyprint, then restore <pre>s content later. Verified in my post jQuery, how to clone back saved elements? .
You can find three examples here
I did it as follows in js:
document.getElementById('outputa').innerHTML =
PR.prettyPrintOne("your code in brackets or your variable (without these brackets)",
'java');
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.
I'm a beginner at jQuery and I'm trying to insert a Facebook like button through the jQuery document.ready function.
My external Javascript file (loaded after the jQuery script) has the following code:
$(document).ready(function(){
if ($('#fb_btn').length) {
var fb_code = "";
fb_code += "<iframe src=\"http://www.facebook.com/plugins/like.php?href=" + escape(document.URL) +"&layout=standard&show_faces=false&width=450&action=like&colorscheme=light&height=80\" scrolling=\"no\" frameborder=\"0\" style=\"border:none; overflow:hidden; width:450px; height:80px;\" allowTransparency=\"true\" >";
$('#fb_btn').prepend(fb_code);
}
});
My HTML code for where I want the button is
<span id="fb_btn"></span>
Currently, nothing seems to load into the span.
I'm trying to use this instead of inserting the code directly because inserting directly slows down the page down a bit too much.
Thanks.
Brian, the errors you're getting on your page seem to be related to the absence of the $ variable. Are you sure you're running your $(document).ready() only after you load your jQuery scripts? Remember...Javascript runs from top to bottom, so if you load your jQuery script after you run anything on the $ or jQuery variables, you will get object undefined errors.
Then, to reiterate what others have said, you should probably close that html string with </iframe> and put the iframe in a block-level element.
I think I just fixed the problem by updating the jQuery on my site. It was version 1.4.2. By using Version 1.4.3, everything seems to work fine.
Either that or there was something modified incorrectly with the jQuery I had.
Thanks for your help everyone.
I'm trying to create a JS-script to make modifications to add a footer to HTML -documents on the fly. The idea is to append a div-element at the end of the document to contain the footer, and to provide a floating fixed footer, I also need to have all of the other content wrapped in a div, basically I need something like this:
<html>
<head>
<title>Foobar</title>
</head>
<body>
<div id="contentWrapper">
<!-- Content is here -->
</div>
<div id="footerWrapper">
<!-- Footer goes here -->
</div>
</body>
</html>
The problem is, that the HTML is generated from a system where the end user's have had a little too much control over the structure (it's a blogging platform), and there's no guarantee of a certain sturcture hence I need to wrap the content in a div to ensure the footer works ok.
What I tried, and realized that doesn't work is:
$(document.body).wrap($('<div/>').attr('id','footerWrapper'));
The problem with this is that due to the fact that the HTML structure is generated by the user, I have been forced to inject links to the JS-file inside the <body>-tag. So now when I call wrap(), it seems that everything is first removed from $(document.body) and then appended in the new div. Since the JS-files are linked from inside , calling wrap() seems to remove them momentarily, and it seems that the scripts are unloaded by the browser and everything stops working and I'm left with a blank page. Not exactly what I had in mind.
Next idea was to first copy the JS-tags to the head-element to preserve them, so I wrapped them in a div (yeah, ugly, I know), and tried to copy them to the :
$(document.head).append($('#copyToHead').html());
That didn't do anything, and seems that $(document.head) isn't usable with functions such as .html() and .append().
So, now I'm out of ideas. Anyone have any ideas?
$(document.head) isn't usable with functions such as .html() and .append().
That would be because document.head is undefined
Use $("head")[0]
not clear on what your are trying to add to the head part. if you are simply trying to add a div to the end here is a solution:
$(document).ready(function(){
$(document.body).append($('<div></div>').attr('id','mydiv').html('This is footer'));
});
idea
If leave fact, that $(document.body) doesn't exist, wrapping everything into div and then setting id through attr might be problematic (don't ask me why—it just happens). So I played with it and created this little snippet (with preview, 100% working).
Since you can't play with html, but can "append" script I did whole document manipulation through inline script.
code
<script type="text/javascript">
$(document).ready(function(){
$("body")
.wrapInner('<div id="wrapper"/>')
.append('<div id="footer">footer text</div>');
});
</script>
preview
http://jsbin.com/ezoqo4/3
edits:
further simplification and proper markup generation
I believe this should serve you better:
$('body')
.children ().wrapAll ($('<div/>').attr('id','contentWrapper'))
.end ()
.append ($('<div/>').attr('id','footerWrapper'))
;
Ref: wrapAll