I'm trying to append xmlTwo inside the xmlOne yellow node, but I'm getting an error. What am I doing wrong?
var xmlOne =
$.parseXML(
"<xml xmlns=\"mynamespace\">\
<red>\
<orange>\
<yellow>\
</yellow>\
</orange>\
</red>\
</xml>"
);
var xmlTwo =
$.parseXML(
"<green>\
<blue>I'm in blue!</blue>\
</green>"
);
var xmlThree = xmlOne.getElementsByTagName("yellow")[0].appendChild(xmlTwo);
console.log(xmlThree);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
Parse the first element, the root one.
Keep the second XML element as string.
Find the node in the first element where you want to append the other XML.
Append the XML into the node.
var xmlOne =
$.parseXML(
"<xml xmlns=\"mynamespace\">\
<red>\
<orange>\
<yellow>\
</yellow>\
</orange>\
</red>\
</xml>"
);
var xmlTwoNotParsed =
"<green>\
<blue>I'm in blue!</blue>\
</green>";
var yellowNode = $(xmlOne).find("yellow");
yellowNode.append(xmlTwoNotParsed);
console.log(xmlOne);
Related
Is there a way to convert HTML like:
<div>
<span></span>
</div>
or any other HTML string into DOM element? (So that I could use appendChild()). I know that I can do .innerHTML and .innerText, but that is not what I want -- I literally want to be capable of converting a dynamic HTML string into a DOM element so that I could pass it in a .appendChild().
Update: There seems to be confusion. I have the HTML contents in a string, as a value of a variable in JavaScript. There is no HTML content in the document.
You can use a DOMParser, like so:
var xmlString = "<div id='foo'><a href='#'>Link</a><span></span></div>";
var doc = new DOMParser().parseFromString(xmlString, "text/xml");
console.log(doc.firstChild.innerHTML); // => <a href="#">Link...
console.log(doc.firstChild.firstChild.innerHTML); // => Link
You typically create a temporary parent element to which you can write the innerHTML, then extract the contents:
var wrapper= document.createElement('div');
wrapper.innerHTML= '<div><span></span></div>';
var div= wrapper.firstChild;
If the element whose outer-HTML you've got is a simple <div> as here, this is easy. If it might be something else that can't go just anywhere, you might have more problems. For example if it were a <li>, you'd have to have the parent wrapper be a <ul>.
But IE can't write innerHTML on elements like <tr> so if you had a <td> you'd have to wrap the whole HTML string in <table><tbody><tr>...</tr></tbody></table>, write that to innerHTML and extricate the actual <td> you wanted from a couple of levels down.
Why not use insertAdjacentHTML
for example:
// <div id="one">one</div>
var d1 = document.getElementById('one');
d1.insertAdjacentHTML('afterend', '<div id="two">two</div>');
// At this point, the new structure is:
// <div id="one">one</div><div id="two">two</div>here
Check out John Resig's pure JavaScript HTML parser.
EDIT: if you want the browser to parse the HTML for you, innerHTML is exactly what you want. From this SO question:
var tempDiv = document.createElement('div');
tempDiv.innerHTML = htmlString;
Okay, I realized the answer myself, after I had to think about other people's answers. :P
var htmlContent = ... // a response via AJAX containing HTML
var e = document.createElement('div');
e.setAttribute('style', 'display: none;');
e.innerHTML = htmlContent;
document.body.appendChild(e);
var htmlConvertedIntoDom = e.lastChild.childNodes; // the HTML converted into a DOM element :), now let's remove the
document.body.removeChild(e);
Here is a little code that is useful.
var uiHelper = function () {
var htmls = {};
var getHTML = function (url) {
/// <summary>Returns HTML in a string format</summary>
/// <param name="url" type="string">The url to the file with the HTML</param>
if (!htmls[url])
{
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", url, false);
xmlhttp.send();
htmls[url] = xmlhttp.responseText;
};
return htmls[url];
};
return {
getHTML: getHTML
};
}();
--Convert the HTML string into a DOM Element
String.prototype.toDomElement = function () {
var wrapper = document.createElement('div');
wrapper.innerHTML = this;
var df= document.createDocumentFragment();
return df.addChilds(wrapper.children);
};
--prototype helper
HTMLElement.prototype.addChilds = function (newChilds) {
/// <summary>Add an array of child elements</summary>
/// <param name="newChilds" type="Array">Array of HTMLElements to add to this HTMLElement</param>
/// <returns type="this" />
for (var i = 0; i < newChilds.length; i += 1) { this.appendChild(newChilds[i]); };
return this;
};
--Usage
thatHTML = uiHelper.getHTML('/Scripts/elevation/ui/add/html/add.txt').toDomElement();
Just give an id to the element and process it normally eg:
<div id="dv">
<span></span>
</div>
Now you can do like:
var div = document.getElementById('dv');
div.appendChild(......);
Or with jQuery:
$('#dv').get(0).appendChild(........);
You can do it like this:
String.prototype.toDOM=function(){
var d=document
,i
,a=d.createElement("div")
,b=d.createDocumentFragment();
a.innerHTML=this;
while(i=a.firstChild)b.appendChild(i);
return b;
};
var foo="<img src='//placekitten.com/100/100'>foo<i>bar</i>".toDOM();
document.body.appendChild(foo);
Alternatively, you can also wrap you html while it was getting converted to a string using,
JSON.stringify()
and later when you want to unwrap html from a html string, use
JSON.parse()
I am getting data from a XML and displaying it, but if I append another div with a var inside a new div, I get [object Object] instead of the XML data. How can I append a div with a new div plus var inside, this is what im trying to do
$('#channels').append('<div id="logo">'+$(this).find("display-name")+'</div>');
below is the full code im using
<div class="channels" id="channels"></div>
var xml = "<tv generator-info-name='tvchannels' source-info-name='tvchannels'><channel id='1234'><display-name>Channel 1</display-name></channel><channel id='5678'><display-name>Channel 2</display-name></channel><channel id='543553'><display-name>Channel 3</display-name></channel><channel id='324324'><display-name>Channel 4</display-name></channel></tv>",
xmlDoc = $.parseXML( xml ),
$xml = $( xmlDoc );
$xml.find('channel').each(function (i,e) {
$('#channels').append('<div id="logo">'+$(this).find("display-name")+'</div>');
});
$(...).find() yields a jQuery object which serializes to [object Object]. You wanted to get the text instead; use text() method on the objects for that:
var xml = "<tv generator-info-name='tvchannels' source-info-name='tvchannels'><channel id='1234'><display-name>Channel 1</display-name></channel><channel id='5678'><display-name>Channel 2</display-name></channel><channel id='543553'><display-name>Channel 3</display-name></channel><channel id='324324'><display-name>Channel 4</display-name></channel></tv>",
xmlDoc = $.parseXML(xml),
$xml = $(xmlDoc);
$xml.find('channel').each(function(i, e) {
$('#channels').append('<div id="logo">' + $(this).find("display-name").text() + '</div>');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="channels" id="channels"></div>
I have tried to retrieve the top level 'label' attribute from the following xml using jquery, and having parsed it into a DOM object with no luck. Any suggestions on how I can do this ? I've tried using children(),parent() functions with no luck - I get either no result, or end up having all instances of the label tags passed back to me.
jquery:
xml = $.parseXML(xmlString);
$xml = $(xml);
I traverse fields via $($xml).find('fields').each(function(){ etc...
but cannot get that top level label data!
<customobject>
<label>want this content</label>
<fields>
<label>foo</label>
<attr1></attr1>
<attr2></attr2>
</fields>
<fields>
<label>foo2</label>
<attr1></attr1>
<attr2></attr2>
</fields>
</customobject>
You can look for label which is a child of customobject like below. Just using find('label') will return contents from all the label elements
var xmlString = '<customobject><label>want this content</label><fields><label>foo</label><attr1></attr1><attr2></attr2></fields><fields><label>foo2</label><attr1></attr1><attr2></attr2></fields></customobject>';
var xml = $.parseXML(xmlString);
var $xml = $(xml);
alert($xml.find('customobject > label').text())
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Hope this will be helpful
var xml = "<customobject>"+
"<label>want this content</label>"+
"<fields>"+
"<label>foo</label>"+
"<attr1></attr1>"+
"<attr2></attr2>"+
"</fields>"+
"<fields>"+
"<label>foo2</label>"+
"<attr1></attr1>"+
"<attr2></attr2>"+
"</fields>"+
"</customobject>";
xmlDoc = $.parseXML(xml ),
$xml = $( xmlDoc ),
$firstLabelbject = $xml.find( "customobject label")[0].innerHTML; // Will select first label
console.log($firstLabelbject);
JSFIDDLE EXAMPLE
How do i loop through the 'roster' tag, and push in to an array, if any 'player' node is found .
How do i check, no child elements in 'roster' tag .
I tried in the following way, but not working,
var strXML = '<root><club><roster/></club>\
<club><roster>
<player code="AUQ" name="AVDALOVIC, VULE" position="Guard"/>\
<player code="AQX" name="SCHULTZE, SVEN" position="Forward"/>\
</roster></club></root>';
var p = new DOMParser();
var doc = p.parseFromString(strXML, "application/xml");
var players=doc.getElementsByTagName("player");
var i=0,arr=[];
for(i=0;i<players.length;i++){
arr.push({
code:players[i].getAttribute("code"),
name:players[i].getAttribute("name"),
position:players[i].getAttribute("position"),
});
}
console.log(arr);
I am getting the output, but the output is coming blank, if any blank values are found.
Your xml has a problem, there should be one root element for the document
var strXML = '<root><club><roster/></club><club><roster><player code="AUQ" name="AVDALOVIC, VULE" position="Guard"/><player code="AQX" name="SCHULTZE, SVEN" position="Forward"/></roster></club></root>';
Demo: Fiddle
I am using a normal variable to display the list of images. But the same thing I need is by using the XML. Can anyone please help me. The var 'imgs' should be an xml.
Jquery
$(function() {
var imgs = ['http://www.academy-florists.com/images/shop/thumbnails%5CValentines_Day_flowers.jpg', 'http://www.everythingbuttheprincess.com/assets/images/babies-in-bloom-fuchsia-flower_thumbnail.jpg', 'http://www.behok.ru/i/a/cat/gerbera.jpg', 'http://www.thebutterflygrove.com/images/thumbnails/0/200/200/thumbnail_flower-decor-makpk.jpg', 'http://gameinfestedent.com/gallery_photo/medium_image/image1322820610_MainPurpleOrchids3_1a.jpg'];
var maximages = imgs.length; //No of Images
Slider();
setInterval(Slider, 3000);
var prevIndex = 0, prevPrevIndex = 0;
function Slider() {
$('#imageSlide').fadeOut("slow", function() {
do {
shuffleIndex = Math.floor(Math.random() * maximages);
} while(prevIndex == shuffleIndex || prevPrevIndex == shuffleIndex)
prevPrevIndex = prevIndex;
prevIndex = shuffleIndex;
$("#panel").fadeIn("slow").css('background', '#000');
$(this).attr('src', imgs[shuffleIndex]).fadeIn("slow");
});
}
});
I am assuming you want the image urls in xml format and then you want to parse this xml.
<images>
<image-url>http://www.academyflorists.com/images/shop/thumbnails%5CValentines_Day_flowers.jpg</image-url>
<image-url>http://www.everythingbuttheprincess.com/assets/images/babies-in-bloom-fuchsia-flower_thumbnail.jpg</image-url>
<image-url>http://www.behok.ru/i/a/cat/gerbera.jpg</image-url>
<image-url>http://www.thebutterflygrove.com/images/thumbnails/0/200/200/thumbnail_flower-decor-makpk.jpg</image-url>
<image-url>http://gameinfestedent.com/gallery_photo/medium_image/image1322820610_MainPurpleOrchids3_1a.jpg</image-url>
</images>
The you can parse it in the following way
var imgs = "<images><image-url>'http://www.academy-florists.com/images/shop/thumbnails%5CValentines_Day_flowers.jpg'</image-url><image-url>'http://www.everythingbuttheprincess.com/assets/images/babies-in-bloom-fuchsia-flower_thumbnail.jpg'</image-url><image-url>'http://www.behok.ru/i/a/cat/gerbera.jpg'</image-url><image-url>'http://www.thebutterflygrove.com/images/thumbnails/0/200/200/thumbnail_flower-decor-makpk.jpg'</image-url><image-url>'http://gameinfestedent.com/gallery_photo/medium_image/image1322820610_MainPurpleOrchids3_1a.jpg'</image-url></images>"
$xml = $.parseXML(imgs)
images = []
$($($xml).find('image-url')).each(function() { images.push($(this).text()) })
images will contain an array of all the image urls
You haven't told us what your xml would look like so I've together the following basic schema
<?xml version="1.0" encoding="utf-8" ?>
<images>
<image>url of image</image>
<image>url of next image</image>
<images>
If you search the jQuery site you will find that it tells you how to work with Xml - http://api.jquery.com/jQuery.parseXML/
You need to use parseXML on your xml string and convert to a jQuery object. You can then find() elements, loop through elements or pickout the elements text and attributes. The following example shows this.
$(function() {
// your image list as xml string
var xmlStr = '<?xml version="1.0" encoding="utf-8" ?><images><image>http://www.academy-florists.com/images/shop/thumbnails%5CValentines_Day_flowers.jpg</image><image>http://www.everythingbuttheprincess.com/assets/images/babies-in-bloom-fuchsia-flower_thumbnail.jpg</image><image>http://www.behok.ru/i/a/cat/gerbera.jpg</image><image>http://www.thebutterflygrove.com/images/thumbnails/0/200/200/thumbnail_flower-decor-makpk.jpg</image><image>http://gameinfestedent.com/gallery_photo/medium_image/image1322820610_MainPurpleOrchids3_1a.jpg</image></images>';
// parse the xml and produce an jQuery image object ($image) to represent the list of image elements
var xmlDoc = $.parseXML(xmlStr),
$xml = $(xmlDoc),
$image = $xml.find("image");
// loop throught your image elements and alert the url
$image.each(function() {
var imageElement = this, // this within the loop is the current element
$imageElement = $(imageElement),
imageUrl = $imageElement.text(); // use text to get the url
alert(imageUrl);
});
// use length on the jQuery object to get the element count
var maximages = $image.length;
alert(maximages);
var shuffleIndex = 3,
imageElement = $image[shuffleIndex], // index the random image that you want to use
$imageElement = $(imageElement),
imageUrl = $imageElement.text();
alert(imageUrl);
});