Let a user copy the source code... of an element with jquery - javascript

I can understand basic javascript and jquery but I'm having a hard time understanding how to allow a user to see the source code of an element for example.
If I have an element on a webpage like this
`<p>Hi I'm an element</p>`
every body knows it will be displayed as this
Hi I'm an element
but I want a user to see this in its source code form
`<p>Hi I'm an element</p>`
How on earth is this done??

The basic idea is to get the HTML of an element, then show it somewhere as plain-text. We can use .html() to get the HTML and then .text() to output the same HTML as plain-text:
//on the click of a link
​$('a')​.on('click', function () {
//append a container with the plain-text HTML of an element
$('body').append($('<div />').text($('form').html()));
});​​
Here is the demo: http://jsfiddle.net/YbJfs/
Note that this does not get the actual <form> tag, but you could place the form in a container, select the container, and then use the .html() if that container and you'll have the <form> tag as well.
Also, if you want to add the HTML to a form input or text-area, you can use .val() rather than .text().
Here is a demo: http://jsfiddle.net/YbJfs/1/

You can use...
element.outerHTML;
...though it isn't technically the "source code". It's the HTML rendered by the browser, which may have some differences.
Also, you need a shim for Firefox 10 and lower.
function outerHTML(el) {
return el.outerHMTL || document.createElement('div')
.appendChild(el.cloneNode(true))
.parentNode
.innerHTML;
}

to grab the html of an element either use native javascripts innerHTML, or if you want to use jQuery use html() method. Examples ...
javascript:
var html = document.getElementById('myOb').innerHTML;
jQuery:
var html = $('#myOb').html();

Related

JavaScript DIV Editing Destroys Functionality of Other Elements

So my website is built using a company's software called Inksoft which leaves me very little to work in the way of customization. So I have to do many workarounds.
Here is my site's homepage.
The header on top of the page only has two links right now. "Products" and "Design Studio". My goal is to add an "About Us" link and "Buyers Guide" to the header as well.
I cannot add new content to the header using Inksoft's backend. So I coded a workaround to replace the content of existing DIV's within the header to say and link to where I want them to go.
The only issue is, the responsive mobile-nav loses functionality when this is implemented. As seen here on this test page.
The test page has the About Us in the top header, added by the use of this code:
<script>
$("#header-nav-designs").html('<document.write="<li id="header-nav-studio"><font color="#000000">About Us</font></li>');
</script>
So, the simplified question is: how do I implement this code without losing the responsive functionality of the nav bar?
The jQuery .html function will replace the HTML inside the target element. If you want to just append the one value, you likely want to .append to the element.
In addition, you aren't setting the HTML to a valid html string. You probably just want to get rid of the <document.write=" at the beginning of the string. The rest of it looks fine with just a cursory glance.
So:
<script>
$("#header-nav-designs").append('<li id="header-nav-studio"><font color="#000000">About Us</font></li>');
</script>
Edit:
After looking at it a little more, it appears as though the $('#header-nav-designs') that you are selecting is already an <li> which means you need to either select the parent <ul> list or you can use the jquery .after function instead.
<script>
$("#header-nav-designs").after('<li id="header-nav-studio"><font color="#000000">About Us</font></li>');
</script>
And as someone else commented above, you are getting an error on the page. It appears as though you are trying to get an element with the id divID and the appending some html to it, but there is no element with the id divID and so you are getting an error saying that you can't read the property innerHTML of null as the call to document.getElementById is returning null (element not found).
Element id header-nav-designs witch your code is referring have CSS style on line 170:
#header-nav-designs {display:none;}
The element will be hidden, and the page will be displayed as if the element is not there. With display:none;
If I understand you correctly your code selector points to wrong element id. It should point $(".header-nav > ul"). Document.write is not needed inside jQuery you need to give only an valid html string as argument.
jQuery html function erase html that is all ready inside element and replace it with html string given as argument. You have to use append if you want to add more html but not remove what is allready in element.
$(".header-nav > ul").append('<li><font color="#000000">About Us</font></li>');
$(".header-nav > ul").append('<li><font color="#000000">Buyers Guide</font></li>');

jQuery get html in div without any markup

I have some script written using the jQuery framework.
var site = {
link: $('#site-link').html()
}
This gets the html in the div site-link and assigns it to link. I later save link to the DB.
My issue is I don't want the html as I see this as being to dangerous, maybe?
I have tried:
link: $('#site-link').val()
... but this just gives me a blank value.
How can I get the value inside the div without any markup?
Try doing this:
$('#site-link').text()
From the jQuery API Documentation:
Get the combined text contents of each element in the set of matched
elements, including their descendants, or set the text contents of the
matched elements.
Use the .text() jquery method like this:
var site = {
link: $('#site-link').text()
}
Here is an example of what .val(), .html() and .text() do: jsfiddle example
Use the text() method.
Get the combined text contents of each element in the set of matched elements, including their descendants, or set the text contents of the matched elements.
Use the .text() function of jQuery to get the only text.
var site = {
link: $('#site-link').text()
}
to avoid html, you will be required to use text() method of jquery.
var site = {
link: $('#site-link').text()
}
http://api.jquery.com/text/
If you are planning to store the result in the database and you are concerned about HTML, than using something like .text() rather than .html() is just an illusion of security.
NEVER EVER trust anything that comes from the client side!
Everything on the client side is replaceble, hijackable by the client rather easily. With the Tamper Data firefox plugin for example, even my mother could change the data sent to the server. She could send in anything in place of the link. Like malicious scripts, whole websites, etc...
It is important that before saving the "link" to the database you validate it on the server side. You can write a regex to check if a string is a valid url, or just replace everything that is html.
It's also a good idea to html encode it before outputting. This way even if html gets into your database, after encoding it will be just a harmless string (well there are other stuff to be aware of like UTF-7, but the web is a dangerous place).

Could be jquery used to modify html strings?

I have for example such piece of html:
var html = '<p>Title</p><b>edit me</b><i>remove me</i>';
I want to change title in it, but do not want to use regexp or string replace
functions for this, because if title would match tag name, then html could be corrupted.
I now trying to adopt jQuery for this, because it seems capable, but in reality things not so easy. Here is code:
$( $(html)[0] ).text('New title');
console.log(html); // --> prints out original html with old title
Any idea how to make this code work if it is at all possible ?
html = $('<div/>').html(html).find('p').text('New title').end().html();
http://jsfiddle.net/bEUHN/
Note: There are 3 wrapper elements in the created jQuery object using $(html), for selecting the p element you should use filter method.
$(html).filter('p').text('New title');

Syntax Highlighter Around A Div Element

I am using the syntax highlighter plugin and I want to always have it applied to a specific div area. The div's content will change based on a on-click hyperlink. How can I enclose the syntax highlighter script tag around the "mydiv" element at all times?
<script>
function viewCode() {
$('#mydiv').load('euler/_48.py');
}
</script>
View Code
<div id="mydiv">
my div's initial content
</div>
<script type="syntaxhighlighter" class="brush: js"><![CDATA[
//always apply this script to mydiv
]]></script>
With syntaxHighlighter, you cannot highlight arbitrary elements on the page, so we will stick to the script method instead.
First, give the script and anchor tag an id, like
Show Code
<script type="syntaxhighlighter" class="brush: js" id="highlighted"></script>
Then, use this to load the contents when the user clicks on the link
$('#show_code').click(function(){
$.get('euler/_48.py', function(data){
$('#highlighted').html('<![CDATA[' + data + ']]>');
SyntaxHighligher.highlight();
});
});
Remember that the usual method to use syntexhighlighter.js would not work here because the SyntaxHighlighter.all() function only binds the highlight() function to the onload event, so you will have to call that function yourself every time the page updates, by adding a call to the SyntaxHighligher.highlight() function everytime you update the page.
Alternatively, I'd usually recommend the pre method. Its almost the same as above, but we use the pre element instead and use the text() jQuery function to get the escaping done correctly. Using the pre element:
<pre class="brush: js" id="highlighted"></pre>
With this piece of Javascript
$.get('euler/_48.py', function(data){
$('#highlighted').text(data);
SyntaxHighligher.highlight();
});
I think you can call HighlightAll method
Example:
dp.SyntaxHighlighter.HighlightAll('code');
Sultan

jQuery appended text is invisible

I'm trying to create a couple of buttons above a textarea to insert some HTML code -- a VERY poor-man's HTML editor. I have a couple of INPUT elements, and I'm using jQuery to set a click handler that will call's jQuery's append() or html() or text() functions.
The handler fires, it shows a debug alert(), but the text I'm trying to append doesn't show up in the textarea. When I inspect the textarea in Firebug, I see the text I'm appending as a child of the textarea -- but it's dimmed, as when an element's style is set to display:none. But Firebug's CSS inspector doesn't show any change to the display or visibility properties.
When I set the click handler to 'append()', and then click multiple times, in Firebug I see the text being added over and over again -- but each new chunk is still invisible. If I choose 'Edit HTML' in Firebug and then type some chars next to the appended text, the entire text block -- the text added by jQuery and the stuff I added in Firebug -- suddenly appear.
This also happens if I don't use a click handler, but call my append function using an inline handler like onclick="javascript:insert('bold');"
Anyone have any idea why the appended text is not displayed?
Here's the relevant code:
The HTML:
<input type='button' id='bold' value='B' onclick='javascript:insert("bold")' />
<textarea name='PersonalGreeting' id='PersonalGreeting'>default text</textarea>
The Javascript:
function insert( cmd ) {
switch ( cmd ) {
case 'bold':
$('#PersonalGreeting').append('<b>bold text here</b>');
break;
}
}
I would guess that jQuery is trying to append HTML DOM elements to the textarea.
Try using the val method to get and set the textarea's value, like this:
$('#PersonalGreeting').val($('#PersonalGreeting').val() + '<b>bold text here</b>');
The basic problem is that you can't put HTML inside a <textarea>. In fact, you can't append HTML elements to one at all. You could use the .val() method to change the text shown inside, but that won't make it bold. That will just make it have <b> showing as part of the text.
An off-the-shelf WYSIWYG editor like TinyMCE is free and easy to implement. Rather than reinvent the wheel (which is a lot harder than it might look), try an existing wheel out.
SLaks and VoteyDisciple are correct. You're usage of append is faulty as you are perceiving it as a string function.
From http://docs.jquery.com/Manipulation/append
Append content to the inside of every
matched element. This operation is the
best way to insert elements inside, at
the end, of all matched elements. It
is similar to doing an appendChild to
all the specified elements, adding
them into the document.
Reinventing the wheel on this one is likely more headache than its worth unless this is an attempt to create a superior, competing product or for your own experimentation.
Also, I would shy away from use of obtrusive JavaScript as you have shown in your example with onclick='javascript:insert("bold")' embedded in the input element. Instead, you'll have a more elegant solution with something like the following:
HTML
<input type="button" value="B" class="editor-command" >
<input type="button" value="I" class="editor-command" >
<input type="button" value="U" class="editor-command" >
JavaScript (not tested)
$(document).ready(function() {
var textarea = $('#PersonalGreeting')
$(".editor-command").each(function(i, node) {
textarea.val(textarea.val() + '<$>text here</$>'.replace(/\$/g, node.value);
});
});
If the main issue is the textarea not being visible, I would try this:
$('#PersonalGreeting').append('<b>bold text here</b>').show();
Might be worth a shot.
edit: In the vain of not trying to reinvent the wheel, I've had success with WYMEditor
You could do this:
$('#PersonalGreeting').append('[b]bold text here[/b]');
But that won't actually render the text as bold. To be honest I'm not actually sure how to render text as bold inside a textarea, I imainge some js trickery.

Categories