process html string before insertion - javascript

I want to load some html from server, I store the loaded html in a string then I want to modify the values of certain tags and elements within that string before appending it :
here is how I'm trying to do it :
script of test1.html :
<head>....</head>
<body> <div id="main"></div></body>
<script>
$(document).ready(function(){
$.get("test2.html").done(function(data){
$("#rf", data).val("new value");
$("#main").append(data);
});
});
</script>
test2.html
<p id="rf"> <b>old value</b></p>

The first problem is trying to target the val() method of a paragraph. That will not do anything as it has no val property to return. You need to use text or html to replace the content.
Second, convert the HTML string to a DOM tree first with $(data) (see notes below as to why I use a dummy div and html() instead), then find the element, change it etc then append the new tree to the target:
JSFiddle: http://jsfiddle.net/TrueBlueAussie/NWj62/1/
var html = '<p id="rf"> <b>old value</b></p>'
$(document).ready(function () {
var $html = $("<div>").html(html);
$html.find("#rf").html("new value");
$("#main").append($html);
//$.get("test2.html").done(function(data){
// $("#rf", data).val("new value");
// $("#main").append(data);
//});
});
You need to wrap the incoming HTML in a dummy div as find will not match the top element of the tree.
I substituted dummy data so you could see it working without the ajax call.
Note: $(htmlstring) will collapse html and body tags into a flatter structure than you might expect, but your example only has the paragraph so is fine.
Your code will be something like:
$(document).ready(function () {
$.get("test2.html").done(function(data){
var $html = $("<div>").html(data);
$html.find("#rf").html("new value");
$("#main").append($html);
});
});

You want some sort of template functionality, since getting HTML from server and transforming it into a DOM tree and then applying manipulations manually is a lot of code repetition for nothing. Also, it's relatively expensive to do dynamic tree manipalations.
Either the html is processed on the server or on the client side, is your choice.
Backend templates: depends on your backend framework (ie. Django has its own template module).
Fronted templates: You can use Underscore templates or Handlebars templates (more similar to Django templates).

Related

How to handle input parameters while generating dynamic html from jquery function

I am using below function to generate dynamic HTML.
function (content) {
$('#divMessage').append('<span>'+ content+ '</span>');
}
Here I am appending content in div with id divMessage.
Here input parameter content can be any text passed to this function.
I am facing problem when I pass data containing html elements as it distorts html. I am not aable to paste it here as its get dostorted here in stack overflow editor as well.
How can I resolve this issue, TIA.
It should append what is being passed, don't want to convert html tags to html, if html tag with data is passed then html tag with data should be the ouput.
To resolve this you need to only paser the content text to HTML
Just do this
content= $.parseHTML(content);
$('#divMessage').append('<span>'+ content+ '</span>');
Hope it will help!
You can pass html value like this.
function AddContent(content) {
$('#divMessage').append('<span>'+ content+ '</span>');
}
$("#divAppendMessage").on("click", function() {
//$('#divMessage').html(''); // If you want to clear div before append
var html='';
html+='<h1>My new message</h1>';// You can add mark up like this.Be sure for closing tag.
AddContent('<h1>My new message</h1>');// Pass html without generate markup as OP say on comment.
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='divMessage'>
</div>
<button id='divAppendMessage'>Add Message</button>
May be
this fiddle solve your problem. Before get input from user convert it and reset it when bind.

How do I render text on the page of other sites (once script planted)

I am learning javascript and trying to build a chat app like intercom.
How do i go about creating a popup on another page once my js script is planted??
I do it locally like so:
function Hide()
{
document.getElementById('div1').style.visibility="hidden";
}
There is many way to do it i'll explain the idea with some examples, let's go
Our code based on two functionalities:
1: innerHtml = "<YOUR CODE/>"; This property is for injecting the html in the element more info.
2: document.getElementById("IdName") This property is for selecting and element wich we will apply some functionalities, in our case is the property N°1 more info.
3: <div id="IdName"></div> Here where we will append our html or text more info.
Now we start with some examples:
1st example:
API File:
function function_name(argument) {
document.getElementById(argument).innerHTML = "<p>Paragraph example..</p>";
}
User File:
// first of all the user need to put a div with an attribute ID in his html where
//he want to append the html given by the API
<div id="IdName"></div>
//after that he must call the specified function wich is in our case function_name() and put the ID as argument
function_name("IdName"); // this will append the html in the div with the ID == IdName
Also you can use document.getElementsByClassName("className"); in place of ID
2nd example:
In this case the user don't need to put any additional html or any other things; in this example we will add our html into the body element wich is a necessary element in HTML page.
document.body.innerHTML += "<p>Paragraph example..</p>";

How to use xsl:copy-of to copy text of XML node and pass to form? Use CDATA instead?

I am trying to use <xsl:copy-of> to submit copies of two XML nodes along with a form. The problem is that I'm only getting the node's text content instead of all of the full node content. According to w3schools:
The <xsl:copy-of> element creates a copy of the current node.
Note: Namespace nodes, child nodes, and attributes of the current node
are automatically copied as well!
But, this doesn't seem to be happening for me -- either I don't understand the note, or I'm using the <xsl:copy-of> element incorrectly. I've included snippets of my xml, xsl, and jQuery below (I apply the xsl to the xml, which creates an html form, which uses jQuery to submit). I've also included the output I'm currently getting along with the desired output. Any suggestions are much appreciated!
The XML looks like this:
<trigger offsetBeg="89" offsetEnd="96">induced</trigger>
<ggps>
<ggp role="Theme" offsetBeg="68" offsetEnd="73" id="10013"
consensusName="HDAC6">HDAC6</ggp>
<ggp role="Cause" offsetBeg="100" offsetEnd="103" id="7001"
consensusName="TSA">TSA</ggp>
</ggps>
The XSL looks like this:
<xsl:variable name="trigger"><xsl:copy-of select="trigger" /></xsl:variable>
<xsl:variable name="ggps"><xsl:copy-of select="ggps" /></xsl:variable>
<form name="label_form" action="">
<input class="trigger" type="hidden" name="trigger" value="{$trigger}" />
<input class="ggps" type="hidden" name="ggps" value="{$ggps}" />
<div><button class="button">Submit</button></div>
</form>
When I add this to the XSL:
<xsl:copy-of select="current()/trigger"></xsl:copy-of>
<xsl:copy-of select="current()/ggps"></xsl:copy-of>
I get this HTML:
<trigger offsetBeg="89" offsetEnd="96">induced</trigger>
<ggps>
<ggp role="Theme" offsetBeg="68" offsetEnd="73" id="10013"
consensusName="HDAC6">HDAC6</ggp>
<ggp role="Cause" offsetBeg="100" offsetEnd="103" id="7001"
consensusName="TSA">TSA</ggp>
</ggps>
I'm using jQuery to do the form submission:
$(".button").click(function() {
var trigger = $(this).parent().siblings("input.trigger").val();
var ggps = $(this).parent().siblings("input.ggps").val();
var dataString = 'trigger=' + trigger + '&ggps=' + ggps;
$.ajax({
type : "POST",
url : "/submit_label",
data : dataString,
success : function(){
console.log("dataString:\n" + dataString);
}
});
return false;
});
What I'm getting out of console.log is this:
dataString:
trigger='induced '&ggps=' HDAC6 TSA '
What I want to get from console.log would be this:
dataString:
trigger='<trigger offsetBeg="89" offsetEnd="96">induced</trigger>'&ggps='<ggps>
<ggp role="Theme" offsetBeg="68" offsetEnd="73"id="10013"consensusName="HDAC6">
HDAC6</ggp><ggp role="Cause" offsetBeg="100" offsetEnd="103" id="7001"
consensusName="TSA">TSA</ggp></ggps>'
I want this, because I want to be able to drop these nodes directly into another XML document that I'll be building.
Your variable $trigger contains a full copy of the relevant tree, but when you use an attribute value template like this:
value="{$trigger}"
the value is flattened to a string - specifically, the string value of the root element, which is the concatenation of its descendant text nodes.
If you want the attribute to contain a serialised version of the tree (that is, lexical XML including markup, presumably escaped to make it a legal attribute value), then you need to invoke some kind of serialize-xml() function. There is such a function in XSLT 3.0, and in some products such as Saxon; or you could write your own.

Use getElementById() on non-current HTML document

Essentially, I want to pull text within a div tag from a document on my server to place it in the current document. To explain the reason: I want to pull a headline from a "news article" to use it as the text for a link to that article.
For example, within the target HTML is the tag:
<div id='news-header'>Big Day in Wonderland</div>
So in my current document I want to use javascript to set the text within my anchor tags to that headline, i.e.:
<a href='index.php?link=to_page'>Big Day in Wonderland</a>
I'm having trouble figuring out how to access the non-current document in JS.
Thanks in advance for your help.
ADDED: Firefox style issue (see comment below).
I'm not sure where you're getting your HTML but, assuming you already have it in a string, you could create a document of your own, stuff your HTML into it, and then use the standard getElementById to pull out the piece you want. For example:
var doc = document.implementation.createDocument('http://www.w3.org/1999/xhtml', 'html', null);
doc.documentElement.innerHTML = '<body><div>Nonsense</div><div id="news-header">Big Day in Wonderland</div><p>pancakes</p></body>';
var h = doc.getElementById('news-header');
// And now use `h` like any other DOM object.
Live version: http://jsfiddle.net/ambiguous/ZZq2z/1/
Normally, I would try to solve an issue only with the tools specified by the user; but if you are using javascript, there really is no good reason not to just use jQuery.
<a id='mylink' href='url_of_new_article' linked_div='id_of_title'></a>
$(function() {
var a = $('#mylink');
a.load(a.attr('href') + ' #' + a.attr('linked_div'));
});
That little function up there can help you update all your link's text dynamically. If you have more than one, you can just put it in a $('a').each() loop and call it a day.
update to support multiple links on condition:
$(function() {
$('a[linked_div]').each(function() {
var a = $(this);
a.load(a.attr('href') + ' #' + a.attr('linked_div'));
});
});
The selector makes sure that only the links with the existence of the attribute 'linked_div' will be processed.
You need to pull the content of the remote document into the current DOM, as QuentinUK mentioned. I'd recommend something like jQuery's .load() method

Extracting Metadata from Website

I was wondering if there's a way in javascript that allows me to process the html source code that allows me to take out specific tags that I want?
Sorry if it sounds easy or too simple. i am new to programming.
If you have the HTML in a string, then you can use:
var str = '<html></html>'; // your html text goes here
var div = document.createElement('div');
div.innerHTML = str;
var dom = div.firstChild; // dom is the object you want,
// you can manipulate it using standard dom methods
Alternately, use jQuery. jQuery is a library to help you manipulate and access HTML elements more easily. First, add this to the head of your document:
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
This is a reference to the jQuery library. Then, do:
var foo = $("<html>Your html here</html>");
Or, if your html is in a variable (e.g. str), you can do:
var foo = $(str);
Then, you can manipulate and parse foo in a number of ways. For example, to remove all paragraph elements, you would use
foo.remove('p');
Or, to remove the paragraph element with id="bar", use:
foo.remove('p.bar');
Once you are done your modifications, you can get the new html text using:
foo.html();
Why is your html in a string? Is it not the html of the current page?
Use DOM it can pull data from webpages if you know the structure.

Categories