IE - JQuery appending child nodes to XML in $.each loop - javascript

I'm having a problem with IE not correctly appending or recognizing my attempts to append child nodes into a parsed XML string. Chrome and Firefox understand what I'm attempting to do. I don't know if this is a scope issue or a behavior of IE and XML.
var dataContainers = $('[data-container]');
var containerXML = $.parseXML('<inlineSubmission><userid>'+userID+'</userid><guid>'+GUID+'</guid><contentField><![CDATA[FlexXML]]></contentField><content><containers></containers></content></inlineSubmission>');
$.each(dataContainers,function (key,value) {
var containerID = $(value).attr('id'),
isVisible = $(value).is(':visible'),
xmlFragment;
xmlFragment = '<container><name>'+containerID+'</name><visible>'+isVisible+'</visible></container>';
$(containerXML).find('containers').append(xmlFragment);
});
console.log(containerXML)
Chrome and Firefox both correctly return:
<inlineSubmission><userid>55555</userid><guid>22222-222-2-22-222</guid><contentField><![CDATA[FlexXML]]></contentField><content><containers><container><name>heroContainer</name><visible>true</visible><bgcolor>undefined</bgcolor><textcolor>undefined</textcolor><subitem><name>contactInfo</name><visible>none</visible><location>undefined</location></subitem></container><container><name>contentContainer</name><visible>true</visible></container><container><name>cnmContainer</name><visible>true</visible></container><container><name>accountAccessContainer</name><visible>true</visible></container><container><name>promoContainer</name><visible>true</visible></container><container><name>contactContainer</name><visible>true</visible></container></containers></content></inlineSubmission>
While IE is returning the original variable value:
<inlineSubmission><userid>55555</userid><guid>22222-222-2-22-222</guid><contentField><![CDATA[FlexXML]]></contentField><content><containers /></content></inlineSubmission>
Any help would be appreciated!

Try substituting $(containerXML.documentElement) for $(containerXML) .
$(containerXML) returns #document , having context of document , e.g.;
$(document).append("<p>abc</p>")
would not append <p>abc</p> to <html> or <body> elements , and may return error:
TypeError: Cannot read property 'createDocumentFragment' of null .
$(containerXML.documentElement) returns <inlinesubmission> element , having context of inlinesubmission
var userID = "abc", GUID = 123, containerID = 456, isVisible = true;
var xmlFragment = '<container><name>'
+containerID+'</name><visible>'
+isVisible+'</visible></container>';
var containerXML = $.parseXML('<inlineSubmission><userid>'
+userID+'</userid><guid>'
+GUID+'</guid><contentField><![CDATA[FlexXML]]>'
+'</contentField><content><containers></containers>'
+'</content></inlineSubmission>');
console.log($(containerXML)
, $(containerXML.documentElement).find("containers"));
$(containerXML.documentElement).find("containers").append(xmlFragment);
$("body").append($(containerXML.documentElement));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

Finally got it working. Thanks for the answers! They gave me the right direction to move in:
var containerXML = $('<inlineSubmission><userid>'+userID+'</userid><guid>'+GUID+'</guid><contentField>FlexXML</contentField><content><containers></containers></content></inlineSubmission>');
$.each(dataContainers,function (key,value) {
var containerID = $(value).attr('id'),
isVisible = $(value).is(':visible'),
xmlFragment;
xmlFragment = $('<container><name>'+containerID+'</name><visible>'+isVisible+'</visible></container>')
$(containerXML).find('containers').append(xmlFragment);
});
var parsedXML = $.parseXML(containerXML[0].outerHTML);
console.log(parsedXML)

Related

How can I add data params to an HTML string and get a string back?

I got a string like this:
var select_string = '<select><option>1</option><option>2</option></select>';
I need to add some data params to select in this string and get this string back in order to get the following:
select_string = '<select data-param1="param1" data-param2="param2"><option>1</option><option>2</option></select>';
I tried to use jQuery functions like .html() or .text() but it did not work. Like this:
select_string = $(select_string).data('param1', 'param1').html() //or .text()
Any ideas how to make it work would be helpful. Thank you.
You can use attr to add that attributes to the element
var select_string = '<select><option>1</option><option>2</option></select>';
var select = $(select_string).attr({
'data-param1': 'param1',
'data-param2': 'param2'
});
console.log(select.prop('outerHTML'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Since your attribute name starts with data-, if you want to get the value, you can use:
select.data('param1'); // param1
select.data('param2'); // param2
EDIT: Titulum is right, jquery is not needed here.
But here is the working example usign jquery
var selectString = '<select><option>1</option><option>2</option></select>';
var $select = $(selectString);
$select.attr("prop_key","prop_value");
var selectChanged = $select.prop('outerHTML');
console.log(selectChanged)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
You don't need jQuery for this:
const myElement = document.createElement('div');
myElement.innerHTML = "<select><option>1</option><option>2</option></select>";
const selectElement = myElement.getElementsByTagName("select")[0];
selectElement.setAttribute("data-param1", "param1");
selectElement.setAttribute("data-param2", "param2");
You could use indexOf and substr() to split it into 2 parts, insert your new text, and put it back together again.
var first_half = select_string.substr(0, select_string.indexOf('>'));
var second_half = select_string.substr(select_string.indexOf('>'));
select_string = first_half + ' data-param1=\"param1\" data-param2=\"param2\" ' + second_half;

Cannot get the number of var using javascript

I have this certain problem where I cannot get the number value of 'currentStock' var data inside an HTML file using JavaScript. I have this on my HTML file in script tag:
By the way, due to the HTML being too large, and also it was not originally my script, but from a friend who was asking for some help on adding some features in it, I can't upload the whole script as it will be going to be too long. The whole HTML script has 14076 characters with 289 lines.
I have only studied java and not javascript with HTML, so I need help with this one.
<script>
window.onload = function() {
var goDown = document.getElementById('uniqueNav');
var goRight = document.querySelector('.clothesNav');
var goUp = document.querySelector('.shrink');
goDown.style.marginTop = "0px";
goRight.style.marginLeft = "5px";
goUp.style.height = "0px";
}
$('document').ready(function(){
var name = "Ombre Printed Shirt";
var price = "P499.00";
var initialStock = 0;
var currentStock = initialStock;
document.querySelector('#clothTitle').innerHTML = "" +name;
document.querySelector('#clothPrice').innerHTML = "Price: " +price;
document.querySelector('#PITitle').innerHTML = "" +name;
document.querySelector('#PIPrice').innerHTML = "Price: " +price;
document.querySelector('#currentStock').innerHTML = "CurrentStocks: " +currentStock;
}); //------------------------Change This Every Document ----------------------------//
</script>
then this in my JavaScript File:
var cStocks = document.getElementById('currentStock').data;
alert(typeof cStocks);
alert("Data in cStocks = " + cStocks);
if (!cStocks) {cStocks = 0; alert("cStocks, not a valid number");}
if ((cStocks <= 0) == true)
{
document.querySelector('.clothButton').style.display='none';
document.querySelector('.clothButtonDisabled').style.display='flex';
}
else
{
document.querySelector('.clothButton').style.display='flex';
document.querySelector('.clothButtonDisabled').style.display='none';
}
upon loading the page, the alert says thaat the data type is undefined. I don't know what's happening with my code. did I miss something?
By the way, I have JQuery on my HTML page. it says JQuery v3.3.1 as a version
It doesn't look to me like #currentStock will have a data attribute, or value attribute (which is for inputs), so of course the js returns undefined. Right now it looks like #currentStock is having the innerHTML set on the document.ready to Current Stocks: 0
You do have an accessible variable, currentStock, which is defined during document.ready. Why aren't you accessing it directly? It will have the numeric value in it already. All you can get from #currentStock is the html you generated on document.ready, and you'd have to parse the number out of it, when it's available in raw form in the js variable currentStock.

Javascript to get youtube video id (regex issue)

I use:
<script type="text/javascript">
document.addEventListener("DOMContentLoaded", function(event) {
var field1 = document.getElementById("field_wy4dm0");
field1.addEventListener("change", combineFields);
function combineFields() {
var val1 = field1.value;
var val1re = val1.match("/(.*)?")[1];
var str = document.getElementById("changeThisMovie").innerHTML;
var res = str.replace("yeC3AisTs2Y", val1re);
document.getElementById("changeThisMovie").innerHTML = res;
}
});
</script>
It works great to get a youtube video id which is located between "/" and "?" in the "val1" var and replace the old video id "yeC3AisTs2Y" that is located inside a div with the id="changeThisMovie" with the new one ("val1re").
The problem is it adds "?" in the end of the new video id so instead of getting:
/videoid?feature=embed...
I get:
/videoid??feature=embed...
How do i fix this?
Thanks!!!
I think you want to escape the ? In your regex to mean the literal ? symbol - regex will interpret as ignore previous block
So you could try as follows:
var val1re = val1.match("/(.*)\?")[1];

check the XML nodes are empty in javascript

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

getElementById() .innerHTML/.src

I'm trying to create a simple javascript game for college and am having trouble getting what i want to display on screen.
my script is as follows:
var qArray = new Array();
qArray[0] = {image:"Images/q1.png"};
qArray[1] = {image:"Images/q2.png"};
qArray[2] = {image:"Images/q3.png"};
qArray[3] = {image:"Images/q4.png"};
qArray[4] = {image:"Images/q5.png"};
var count = 0;
var question = qArray.splice(count,1);
when i use this i get "undefined":
document.getElementById("question").innerHTML = question.image;
and when i use this i get nothing:
document.getElementById("question").src = question.image;
my html is just a simple div like so:
<div id = "question" align = "center">
</div>
i need to have the "count" variable because it increments to show the next image for the next question
if anyone could help that would be great
Here is a working Fiddle. qArray.splice() doesn't work because it actually removes that element from the array and returns a new array while you were just looking for a specific index in the array (not to mention you just deleted the element you were looking for)
This works. I used a random imgur image to show that it does indeed load.
<html><head></head><body>
<img src="" id="question"></img>
<script type="text/javascript">
var qArray = new Array();
qArray[0] = {image:"http://i.imgur.com/pGpmq.jpg"};
qArray[1] = {image:"Images/q2.png"};
qArray[2] = {image:"Images/q3.png"};
qArray[3] = {image:"Images/q4.png"};
qArray[4] = {image:"Images/q5.png"};
var count = 0;
var question = qArray[count];
document.getElementById('question').src = question.image;
</script>
</body>
</html>

Categories