I have a HTML Textarea in which the list appears like this :
jack=rider
steven=conrad
nancy=gagan
I have to create a button, which once pressed it should show the text in XML any way, In a file or in the same textbox.
<list1>jack=rider</list1>
<list2>steven=conrad</list2>
and so on.
The coding has to in javascript. Please help.
I don't get completely this question, by the way if your aim was to turn a HTML document object, and whatever contents it has in XML, this is pretty straightforward if you have the right tools. We are using Wicked Google Xpath here, a pure JS implementation of the DOM Level 3 XPath specification.
So let's see how it works here, this can help you to build your contents from HTML code, but again, I'm not sure if this was your objective:
var console = {
log: function(s) {
document.getElementById("console").innerHTML += s + "<br/>"
}
}
console.log("XML:installing parser...");
wgxpath.install(window)
console.log("XML:Parser installed.");
console.log("XML:Evaluating XPath...");
var expression = window.document.createExpression('//*[#id="contents"]');
console.log("XML:Evaluating XPath text");
var result = expression.evaluate(document,
XPathResult.STRING_TYPE);
console.log("XML:Contents <br><br>" + result.stringValue);
console.log("<br><br>XML:DONE.");
var expressionXML = window.document.createExpression('//*[#id="contents"]/node()');
console.log("XML:Evaluating XPath node()");
var resultXML = expression.evaluate(document,
XPathResult.ANY_TYPE);
console.log("XML:Contents <br><br>" + resultXML.iterateNext().textContent);
console.log("<br><br>XML:DONE.");
<script src="https://github.com/google/wicked-good-xpath/releases/download/1.3.0/wgxpath.install.js"></script>
<div id="console" />
<div id="contents" style="display:none;"><textarea rows="4" cols="50">
At w3schools.com you will learn how to make a website. We offer free tutorials in all web development technologies.
</textarea>
</div>
Related
I have made a textbox and an iframe in the same html. I want to load the 'html' rendered from textbox into html. I am using javascript button click event, but nothing is getting rendered. Pls help, I cant find where I am making mistake!
HTML:
<button onClick="convert()">Run</button>
<textarea id="mycode">
Hello World!
</textarea>
<iframe id="display"></iframe>
Javascript:
function convert()
{
var x = document.getElementById('mycode').value;
document.getElementById('display').innerHTML = x;
}
Can someone help, what's wrong ?
Try setting src of iframe to data URI representation of textarea value x
function convert()
{
var x = document.getElementById('mycode').value;
document.getElementById('display').src = "data:text/plain," + x;
}
<button onClick="convert()">Run</button>
<textarea id="mycode">
Hello World!
</textarea>
<iframe id="display"></iframe>
Just replace
document.getElementById('display').innerHTML = x;
with
document.getElementById('display').contentWindow.document.body.innerHTML = x
You can't manipulate an iframe with Javascript (or jQuery) because the iframe is essentially a separate webpage. This is for security purposes, to prevent one website from embedding a malicious script into an iframe that can target the host page. There is no way around it, as far as I know. Generally it's not good practice to use iframes.
I was browsing the answers for the same task. Well the accepted answer does help a little but the main task is to render "HTML". It works using the srcdoc attribute of the iframe tag.
function convert()
{
var x = document.getElementById('mycode').value;
document.getElementById('display').srcdoc = x;
}
<button onClick="convert()">Run</button>
<textarea id="mycode">
<!-- Comment is not rendered -->
Hello World!
</textarea>
<iframe id="display"></iframe>
I am converting an old programmer's joke program created here in Brazil that is simmilar to MIT's SCIgen but using artistic jargon instead of businnes gibberish.
As the program is far too old (geocities era old) it uses lots of document.write instead of innerHTHML of course.
First question is, is it safe to place like tons of code inside of innerHTMLs? As the original program loads 4 sets of arrays with every possible piece of text that can be combined to form a pseudo-essay, this is a piece of code:
new_window.document.write("<body bgcolor=\"#000000\">");
new_window.document.write("<body text=\"#00FF00\">")
new_window.document.write("<p align=\"center\"><b>"+atitle+"</b><hr></p>");
firstshot = 1;
paragraph = 0;
while(lines > 0) {
if (firstshot == 1) {
if (lines % 101 == 0 && lines % 19 == 0) {
new_window.document.write(tab0.chr(1,0)+tab0.chr(0,1)+tab3.chr(0,0)
.....
...
this continues in a inch long non nested chunk of code, the entire code is here http://jsfiddle.net/jmqdx09g/
I'm experimenting and this is what I got so far:
<body>
<div id="target"></div>
<div id = "myDiv"></div>
<span id = "mySpan"></span>
<br>
<button id="restore">restore</button>
<p> </p>
<form name="form1" method="post" action="">
<input type="submit" name="remove" id="remove" value="remove">
</form>
<p> </p>
</body>
<script type = "text/javascript">
var message =
'<li>Home</li>'+
'<li>About</li>'+
'<li>Contact</li>'+
'<li>Works</li>'+
' <li>Projects</li>'+
'<li>Curriculum</li>'
var message2 =
'<div class="content">'+
'<iframe src="/yourpage.html" frameborder="0" width="600" height="650" scrolling="no">'+
'<p>Your browser does not support iframes.</p>'+
'</iframe></div>'
document.getElementById("myDiv").innerHTML = message; // use innerHTML for block and inline HTML elements
document.getElementById("remove").addEventListener("click", function ()
{
document.getElementById("myDiv").innerHTML = message2;
});
document.getElementById("restore").addEventListener("click", function ()
{
document.getElementById("myDiv").innerHTML = message;
});
and it works as expected which is load a few html stuff, on a press of a button stuff is replaced by an iframe
is the iframe the best solution for this or replacing the entire html with js is the way to go?
the
var message =
'somecode'+
'somecode'+
looks safe until now, but as far as I get into the converting, am I going to have headaches or this method is straight forward as it looks like?
should I use window.onload instead of replacing the content holder div?
My two cents worth...
Is it safe to place like tons of code inside of innerHTMLs?
Safe, yes... Easily maintainable, no. Front end code is for the client so if they choose to hack themselves let them... Of course anything that is sent back to the server should be sanitised and not trusted, but that is a completely different issue.
In my opinion the greatest problem is maintainability.
Next the JS, refactor this into a separate file, start caching variables makes the code easier to look at.
Finally, do you need the iFrame? Or a new window? Couldn't you simply append the "artistic jargon" to the bottom of the current html? Thus saving the headache of the iframes.
I am a complete advocate of non-jQuery, but maybe for you using jQuery's HTML editing API might be a great idea. Could help to abstract some issues into a more readable and maintainable form. Then again, vanilla JS is really awesome and if it can be done that way its a great way to learn.
Is it alright to define and use custom tags? (that will not conflict with future html tags) - while replacing/rendering those by changing outerHTML??
I created a demo below and it seems to work fine
<!DOCTYPE HTML>
<html lang="en-US">
<head>
<script type="text/javascript" src="jquery.min.js"></script>
</head>
<body>
<div id="customtags">
<c-TextField name="Username" ></c-TextField> <br/>
<c-NameField name="name" id="c-NameField"></c-NameField> <br/>
<c-TextArea name="description" ></c-TextArea> <br/>
<blahblah c-t="d"></blahblah>
</div>
</body>
<script>
/* Code below to replace the cspa's with the actual html -- woaah it works well */
function ReplaceCustomTags() {
// cspa is a random term-- doesn;t mean anything really
var grs = $("*");
$.each(grs, function(index, value) {
var tg = value.tagName.toLowerCase();
if(tg.indexOf("c-")==0) {
console.log(index);
console.log(value);
var obj = $(value);
var newhtml;
if(tg=="c-textfield") {
newhtml= '<input type="text" value="'+obj.attr('name')+'"></input>';
} else if(tg=="c-namefield") {
newhtml= '<input type="text" value="FirstName"></input><input type="text" value="LastName"></input>';
} else if(tg=="c-textarea") {
newhtml= '<textarea cols="20" rows="3">Some description from model</textarea>';
}
obj.context.outerHTML = newhtml;
}
z = obj;
});
}
if(typeof(console)=='undefined' || console==null) { console={}; console.log=function(){}}
$(document).ready(ReplaceCustomTags);
</script>
</html>
Update to the question:
Let me explain a bit further on this. Please assume that JavaScript is enabled on the browser - i.e application is not supposed to run without javascript.
I have seen libraries that use custom attributes to define custom behavior in specified tags. For example Angular.js heavily uses custom attributes. (It also has examples on custom-tags). Although my question is not from a technical strategy perspective - I fail to understand why it would strategically cause problems in scalability/maintainability of the code.
Per me code like <ns:contact .....> is more readable than something like <div custom_type="contact" ....> . The only difference is that custom tags are ignored and not rendered, while the div type gets rendered by the browser
Angular.js does show a custom-tag example (pane/tab). In my example above I am using outerHTML to replace these custom tags - whilst I donot see such code in the libraries - Am I doing something shortsighted and wrong by using outerHTML to replace custom-tags?
I can't think of a reason why you'd want to do this.
What would you think if you had to work on a project written by someone else who ignored all common practices and conventions? What would happen if they were no longer at the company to find out why they did something a certain way?
The fact that you have to just go through with JavaScript to make it work at all should be a giant red flag. Unless you have a VERY good reason to, do yourself a favor and use the preexisting tags. Six months from now, are you going to remember why you did things that way?
It may well work, but it's probably not a good idea. Screen readers and search engines may have a hard/impossible time reading your page, since they may not interpret the JavaScript. While I can see the point, it's probably better to use this template to develop with, then "bake" it to HTML before putting it on the server.
I'm using markdown editor in my app.
$(document).ready(function () {
var converter = Markdown.getSanitizingConverter();
var editor = new Markdown.Editor(converter);
editor.run();
});
<div class="wmd-panel">
<div id="wmd-button-bar"></div>
<textarea class="wmd-input" id="wmd-input" rows="7" cols="30"></textarea>
</div>
<div id="wmd-preview" class="wmd-panel wmd-preview" name="Content"></div>
Initially, the textarea field is empty. After I enter some text, everything works as expected:
Firebug shows such html structure:
Now I need to get entered pure markdown text: **where** is it ?. I need it because I think it should be stored in the database (and later retrieved from database and converted to html when showed to the user). I have no idea how can it be reached. How can I get it ?
They've have some Docs which might be helpful to you.
The fancy way would probably be to catch the preConversion event in the event-chain:
converter.hooks.chain('preConversion', function(markdown) {
// Do something wonderful with you markdown variable, and then return it.
return markdown;
});
The less fancy way, but working as expected would be to just retrieve the value of the value parameter of the textarea.
var textarea = document.getElemetById('wmd-input');
var markdown = textarea.value;
the script has to search a string inside the webpage. but that script should not display what string that it is searching. I mean the search string should be in encrypted format or any other format.
but without that search string the webpage should not be displayed or it should display an error on page.
I am going to develop a plugin. If anybody using that plugin in their webpage they must and should place my name or my website name in that page.
is it possible, if so how to encrypt my text (srikanth) inside the script and how to search that string inside the page.
how many possibilities are there to place my name in a webpage with javascript or jquery but it should not visible as it is when anybody check it in source code
There is no way of hiding your name. If the browser can see it, then so can any user.
You can encrypt your name anyway you like. But of course it needs to be decrypted client-side to actually do the search. So anyone with a javascript debugger could uncover your name in moments.
Or slightly more obscurity you could hash your name server-side, in javascript hash the page contents, and then do your search. Given a decent hash the chance of collisions will be small. However, with a debugger you could still figure out the search string no problem. And to be honest this just sounds absurd.
Whatever you're trying to achieve needs to be re-thought.
Anyone can view Javascript source code, therefore it's not really possible to encrypt something using Javascript in a way that is secure. You can obfuscate it, often in horrible ways, but it's always possible to reverse.
If you can, do anything requiring a modicum of security on the server.
As you cant really encrypt a piece of text you can obfuscate the search and do a check.
<!doctype html public "-//w3c//dtd html 3.2 final//en">
<html>
<head>
<!-- some simple styling so the div element does not appear,
you could equally use a hidden form field and not require the styling -->
<style>#h3llo{display:none;}</style>
</head>
<body>
<div>Hello Some simple text
<form action="#" method="post" onSubmit="dosearch();return false;">
<input type="text" id="searchfield" />
<input type="button" name="submit" value="search" onClick="dosearch();return false;" />
</form>
</div>
<div id="h3llo"></div>
<script>
function d2h(d) {return d.toString(16);}
function h2d(h) {return parseInt(h,16);}
// converts the input string into hex vals
function Str2Hex(inputvars) {
var tmp = inputvars;
var str = '';
for (var i=0; i<tmp.length; i++) {
c = tmp.charCodeAt(i);
str += '\\x' + d2h(c);
}
return str;
}
// converts the input field h3llo back to a string
function Hex2Str() {
var tmp = document.getElementById('h3llo').innerHTML;
var arr = tmp.split('\x');
var str = '';
for (var i=1; i<arr.length; i++) {
c = String.fromCharCode(h2d(arr[i]));
str += c;
}
return str.trim();
}
// fills the h3llo field with the encoded string
function populate(inputvars){document.getElementById('h3llo').innerHTML = Str2Hex(inputvars);}
// checks that the submitted search string matches the encoded string
function check(inputval){if(Hex2Str().toString() != inputval.toString()){ alert("Warning: '" + Hex2Str().toString() + "' != '" + inputval.toString() + "'");}else{alert("success");}}
// the action that fills the hidden field and checks the encoded value is the same
function dosearch(){var sval = String(document.getElementById('searchfield').value);populate(sval); check(sval);}
</script>
</body>
</html>
If someone viewed the source they wouldn't at first glance be able to see the search string, though as it has mentioned before this would be easy to reverse it would obfuscate from the casual viewer. Also If the encoded data was hidden by css as in this example or a hidden form field it would never appear on the page or source un-encoded.
I am developing a library to simplify my daily tasks, and one of which is encryption.
I am using caesar encryption for element encryptions.
you may download the minified file and include it in your html.
The usage is like:
<!DOCTYPE HTML>
<html>
<head>
<title>
Element Encryption
</title>
<script type="text/javascript" src="https://raw.githubusercontent.com/Amin-Matola/domjs/master/dom-v1.0.0/dom.min.js"></script>
</head>
<body>
<h1>Let's encrypt the element data</h1>
<p>You may encrypt this paragraph data</p>
<p>This is another paragraph you may encrypt too</p>
<footer>
<!--------- You may include your js here ------------->
<script type="text/javascript">
d("p").encrypt(text = "", depth = 10);
</script>
</footer>
</body>
</html>