Inserting element inside an XML document using Javascript - javascript

Have a XML string like below:
<stages>
<params/>
<test description=""/>
</stages>
I want to add the following XML string after <test desc.../> tag OR before the end of stages i.e. </stages>
<stage id="myId" level="1">
and all subsequent stages.
Post-addition it should like
<stages>
<params/>
<test description=""/>
<stage id="myId" level="1"/>
<stage id=.../>
...
</stages>
I am trying to do something like this:
var stageNode = document.createTextNode(
"<stage id=\"myId\" level=\"1\">")
);
var root = document.getElementsByTagName("test").parentNode;
console.log(document.getElementsByTagName("test")); //<-- giving [] in console log and root is undefined; though the element is there
var stages = root.getElementsByTagName("stage");
root.insertBefore(stageNode,stages.nextSibling);
How can I do this in JavaScript or JQuery?
Using DocumentBuilder or DocumentBuilderFactory is giving me "Unexpected identifier" error. Is there an easier way to do the above using document builder in Javascript (as in Java)?

With jQuery it might look like so:
function addStage(xmlDocument, stageElement){
var parent = $(xmlDocument).find("test").parent(); //picks <test>'s parent
parent.append(stageElement); //appends stageElement to parent
}
var xmlString = '<stages><params/><test description=""/></stages>'; //your XML string
var xmlDocument = $.parseXML(xmlString); //parses your XML string and returns XML document
$("#addStage").click(function(){
var id = $("#stageId").val();
var stageElement = $("<stage id=\"" + id + "\"></stage>"); //creates new element
addStage(xmlDocument, stageElement);
console.log(xmlDocument);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
Stage ID: <input type="text" id="stageId" /> <input type="button" id="addStage" value="Add stage" />
Open browser's console to see the results.

Using Plain Old JavaScript:
var text = "<stages><params/><test description=\"\"/></stages>";
var parser = new DOMParser();
var xmlDoc = parser.parseFromString(text,"text/xml");
var newNode = xmlDoc.createElement("stage");
newNode.setAttribute("id", "myId");
newNode.setAttribute("level", "1");
xmlDoc.documentElement.appendChild(newNode);
newNode = xmlDoc.createElement("stage");
newNode.setAttribute("id", "myId2");
newNode.setAttribute("level", "2");
xmlDoc.documentElement.appendChild(newNode);
console.log(new XMLSerializer().serializeToString(xmlDoc.documentElement));
For reference on adding node at a particular position, refer XML DOM Add Nodes

Related

displaying existing html pages (one at a time) in tool

I am building a tool in which I am trying to open a html file having single column or multiple column. I want to get each section of html file to be displayed in the display section of my tool as we do so in the browser.My javascript code for display page is:
function open(htmlFile) {
var htmlFile1 = htmlFile;
alert(htmlFile1);
var parser = new DOMParser();
var doc = parser.parseFromString(htmlFile, "text/html");
var all = doc.getElementsByTagName("body");
var sections = doc.getElementsByClassName("section");
alert(sections);
}
I think you want to get all section of your HTML page.If there is no custom class or ID on it then you have to get by getElementsByTagName("section").
Below is the code snippet may help you:
var htmlFile="<html><body><p>Hello World!</p><p>We're here</p><section><h1>WWF</h1><p>The World Wide Fund for Nature (WWF) is....</p></section></body></html>";
function open(htmlFile) {
var htmlFile1 = htmlFile;
alert(htmlFile1);
var parser = new DOMParser();
var doc = parser.parseFromString(htmlFile, "text/html");
var all = doc.getElementsByTagName("body");
var sections = doc.getElementsByTagName("section");
$.each(sections, function() {
alert(this.innerHTML);
});
}
open(htmlFile);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>

Convert string to html tags in Javascript

I want to convert the following string to HTML tags and place it inside my div.
<strong>asdfadfsafsd</strong>
I am using the following code to place it inside my div:
var message = "<strong>testmessage</strong&gt";
document.getElementById('message').innerHTML = bericht;
The problem is that I see the following in my div now:
<strong>testmessage</strong>
But I want to see:
testmessage
What is the problem?
var string = "<strong>asdfadfsafsd</strong>",
results = document.getElementById("results")
results.innerHTML = string;
results.innerHTML = results.textContent;
<div id="results"></div>
At first load the it as html. Then fetch it as text and then again load it as HTML :)
Refer HTML Entities
Try createElement
var tag = document.createElement("strong");
var t = document.createTextNode("testmessage");
tag.appendChild(t);
document.body.appendChild(tag);

Get class from <body> tag within HTML string

I have a string of HTML like this
var html = "<html><head></head><body class='getMe'></body></html>";
I want to get the body tags class and I tried doing that like this.
$(html).filter("body").attr("class")
$(html).find("body").attr("class");
But both methods return undefined. Any help?
You do not need to parse into html, rather try RegExp:
var html = "<html><head></head><body class='getMe'></body></html>";
var clazz = html.match(/body\sclass=['|"]([^'|"]*)['|"]/)[1]; //getMe
Here, String.match() gives array of string for given pattern.
body\sclass=['|"]([^'|"]*)['|"] gives ["body class='getMe'", "getMe"]. Using (), you can grab a particular group.
Also works with multiple classes and other attributes:
var html = "<html><head></head><body class='getMe hey there' id='xyz' bgcolor='red'></body></html>";
var clazz = html.match(/body\sclass=['|"]([^'|"]*)['|"]/)[1]; //getMe hey there
Edited
In order to get classes belonging to body tag starting with header-:
var html = "<html><head></head><body class='getMe header header-1 header-two test'></body></html>";
var headers = html.match(/body\sclass=['|"]([^'|"]*)['|"]/)[1].match(/(header\-\w+)/g);
//["header-1", "header-two"]
Try
var html = "<html><head></head><body class='getMe'></body></html>";
var className = $("<html />", {"html":html}).find("body")[0].className;
console.log(className);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
Did you try to put it in a Variable? find the tag without ""
var MyClass = $(body).attr("class");
// or $(html).find(body).attr("class");

Replace XML nodeValue via Javascript

OK, I have an XML/XSLT pairing (inserted into my HTML via Javascript from 2 external files) that creates a button on the page with the nodeValue taken from a tag called 'JobID' (a generated GUID).
<button id="5f8294ca-fe5a-4da9-847b-da99df999000" onclick="markFinished(this.id)" type="button">Finished</button>
Thus returning the id of the button to a function...
function markFinished(clicked_id)
{
cid = clicked_id;
document.write(cid)
}
The XML look like this...
<?xml version="1.0" encoding="utf-8"?>
<CurrentJobs>
<Job>
<JobID>25657287-cc52-415b-8781-be37d5098656</JobID>
<Status>a-current</Status>
</Job>
<Job>
<JobID>5f8294ca-fe5a-4da9-847b-da99df999000</JobID>
<Status>a-current</Status>
</Job>
<Job>
<JobID>05a84779-5801-4645-a7f9-74529ea5298b</JobID>
<Status>a-current</Status>
</Job>
<Job>
<JobID>07df3deb-4935-4504-8822-a73ccea038ae</JobID>
<Status>b-complete</Status>
</Job>
<Job>
<JobID>078c496d-ac60-48e7-b9fe-a0e1f78ff2c5</JobID>
<Status>c-upcoming</Status>
</Job>
<Job>
<JobID>07ec868e-d294-4bb3-807d-00df66f5bab2</JobID>
<Status>c-upcoming</Status>
</Job>
<Job>
<JobID>8bdeee5f-2bf6-4e44-8af8-69f600048dfe</JobID>
<Status>a-current</Status>
</Job>
</CurrentJobs>
I need a way for my function to match the clicked_id to the JobID and replace the nextSibling (Status) with 'b-finished'. Any help here would be greatly appreciated.
You'd do that by parsing the XML and traversing it nodes.
As the value you're looking for is the text, you have to iterate and check each element until a match is found, then get the next element and replace the text content of that
var parser = new DOMParser();
var doc = parser.parseFromString(xml, "application/xml");
function markFinished(clicked_id) {
var cid = clicked_id;
var nodes = doc.getElementsByTagName('JobID'),
match = null;
for (var i=nodes.length; i--;) {
if ( nodes[i].textContent.trim() === clicked_id ) {
match = nodes[i];
break;
}
}
if (match) {
match.nextSibling.textContent = 'b-finished'
}
}
FIDDLE

Why is HTML elements is displayed as text?

I'm working on a form builder website. After a form is built it must be saved in database. When the user clicks on a form name from the list of saved forms the form information is restored from database. One of the variables I will restore is the structure of the form. In javascript I wrote these lines of code:
var prefix_content='<!DOCTYPE HTML>\n<html lang="en-US">\n<head>\n<meta charset="UTF-8">\n<title> </title>\n </head>\n<body>\n ';
var sufex_content=' \n</body></html>';
var dynamic_content=String(text_content);
document.write(prefix_content + dynamic_content + sufex_content );
The variable dynamic_content contains the dynamic structure.
The problem is that prefix_content and sufex_content is displayed as html but dynamic_content is written in the page as text. Any one knows why is that or knows how to solve this problem.
Note: when I write the text in dynamic content statically between single quotes it is displayed as html not text.
If you're seeing the content retrieved from your database as plaintext, instead of HTML, its HTML entities are probably getting escaped somewhere along the way. Check the contents of your text_content variable (e.g. use console.log(text_content) and if you're seeing stuff like <div> instead of <div>, go on and find out where your escaping happens and either remove it or manually unescape.
TRY THIS:
var prefix_content='<!DOCTYPE HTML>\n<html lang="en-US">\n<head>\n<meta charset="UTF-8">\n<title> </title>\n </head>\n<body>\n ';
var sufex_content=' \n</body></html>';
var dynamic_content=String(text_content);
var parser = new DOMParser();
var el = parser.parseFromString(dynamic_content, "text/html");
document.write(prefix_content + el + sufex_content );
Or you can try this too: Using jQuery
var dynamic_content=String(text_content);
var el = $.parseHTML( dynamic_content );
document.write(prefix_content + el + sufex_content );
var content = "<div style='color:red;'>TEST</div>";
var prefix ='<!DOCTYPE HTML>\n<html lang="en-US">\n<head>\n<meta charset="UTF-8">\n<title>TEST</title>\n</head>\n<body>\n';
var suffix ='\n</body></html>';
var all = prefix + content + suffix;
var parser = new DOMParser();
var doc = parser.parseFromString(all, "text/html");
console.log(doc.children[0].outerHTML);
Instead of children[0] you can also go for:
doc.documentElement.outerHTML
Results in:
<html lang="en-US"><head>
<meta charset="UTF-8">
<title>TEST</title>
</head>
<body>
<div style="color:red;">TEST</div>
</body></html>

Categories

Resources