Not able to access an XML Element using .innerHtml with Javascript - javascript

this is my first post here so I hope that I do this right. I have searched for a day or so now and I haven't been able to find any direction so far so I guess it's time to ask. I am not able to access an element in my XML file. I can load the XML file, and get it saved into a variable and then in the debugger I can navigate to the information that I want to load into my DOM but when I try to access it using ".innerHtml" it is returning an empty string. I have also tried making sure that I am pointing to the correct node(?) inside of the XML Element by adding the [0] location to the "batch".
Here is my function:
function getBatchNumber(xml){
let batchHTML = document.getElementById('batch');
let batch = xml.getElementsByTagName('DIALOG5');
var test = batch[0];
batchHTML.textContent = test.innerHtml;
//batchHTML.textContent = "3151414";
}
In the debugger when I hover over "test" I can see that innerHtml is in the tree and has the correct number I am after. Then when I hover over innerHtml it is showing me that it has a value of "".
Thank you for any help or insight into this.

Related

WHY do I get an empty object when searching by element or xpath _____ HTMLSession, requests-html

I just want to verify the element exists somehow. Trying to print it so I can compare against a string or something.
Here is the problematic code.
session = HTMLSession()
r = session.get('https://www.walmart.com/ip/Sony-PlayStation-5-Video-Game-Console/994712501')
r.html.render(timeout=20)# this call executes the js in the page
oos=r.html.xpath('/html/body/div[1]/div[1]/div/div[2]/div/div[1]/div[1]/div[1]/div/div/div/div/div[3]/div[5]/div/div[3]/div/div[2]/div[1]/section/div[2]/div/div/div/div/div')
print(oos)
#print returns []
I try to print(oos.text) and I get a callback error
#'list' object has no attribute 'text'
also tried print(oos.full_text) same error
'list' object has no attribute 'full_text'
Seems like its a list? So I tried to iterate through it.
for i in oos:
print(i)
#Prints absolutely nothing!
Pretty sure the element doesn't exist. Based on an examination of print(html) I believe I am being redirected to a capthcha page.
Therefore I am going to assume that the [] is essentially an empty list and all code is more or less doing what it's supposed to.

How to get element from HTML stored in variable

I am running an API to retrieve email from external system. I managed to get HTML code from the returned JSON and store it in a variable. Now, I would like to run some further operations on this HTML - for example get all elements with
[data-type="whatever"].
It would be easy in html document:
var x = document.querySelectorAll('[data-type="whatever"]');
However the HTML document I want to work with is stored in the variable so the code I write in API does not recognise it as a document. How can I do it? Any suggestions with vanilla JS?
You can try something like this.
let rawDoc = '<html><head><title>Working with elements</title></head><body><div id="div1">The text above has been created dynamically.</div></body></html>'
let doc = document.createElement('html');
doc.innerHTML = rawDoc;
let div1 = doc.querySelector('#div1');
console.log(div1)
What if you use innerHTML? or maybe I don't fully understand the question.
Since you are working without a document you have 2 options.
1. Use regex to get what you need (something like /<.+>.+ data-type="whatever".+<\/.+>/gi) should do (but for an exact match you may need to make something better).
2. Insert the html in a hidden part of the dom and select what you need from it (like in Zohir answer - he provided a good example).
I used following code with angular to store whole html content in a variable and pass it as argument to call API.
var htmlBody = $('<div/>').append($('#htmlBody').clone()).html();
This might work for you as i was working on sending email to pass invoice template so try this.

Cannot insert HTML value into another

I'm trying to have the value of an HTML element equal the value of another. Sounds simple enough but when I try various options, it doesn't work
Here's what I'm trying to do:
I tried a few things. First, I made a javascript function that when they info button is pressed, it simply sets the value of the newname textbox to the title and then I was going to use javascript to trim off the extension. As you can see on the page, it simply outputs {{modal_header}}. I believe this is because when the function is being called, the value hasn't been set yet and that's why it's outputting this. I couldn't find out where else to call the function in order for it to work.
To get around that issue, I tried using PHP to retrieve the name. The only thing I could find related to the name was which in stuck in the value property of newname, but this output only the last file in the directory, no matter what file you selected.
I tried a bunch of different little things, but without any luck. You guys have any ideas?
Website: http://box.endurehosting.com/
HTML: http://pastebin.com/dZ5rKGUY
try this code
$(function(){
var title = $("#title").html();
title = title.substr(0, title.indexOf('.'));
$("#newname").val(title);
})

Javascript json, check all keys for undefined ('null') and set default

Firstoff I'd like to add I've been learning javascript for like only 2 days now. I'm pretty much way ahead of myself with what I'm trying to get but here goes.
I have a json array from which I get data to replace/insert in my page. The first problem I have is that if it comes across an empty ('null') key it will just stop. Will not even try to continu.
document.getElementById("id1")src=json.img1.link;
document.getElementById("id2")src=json.img2.link;
document.getElementById("id3")src=json.img3.link;
json.img2.link is empty ('null' response from json.). javascript will then not replace "id2" but it also won't replace "id3".
I'm now trying to find a solution where it will if nothing else at least set a default.
The script is not continuing executing because it comes to an error --trying to access property link of an undefined object
Try
document.getElementById('id2').src = json.img2 ? json.img2.link : 'defaultLink';
This way your are checking for undefined (ie null) object in img2 and assigning the default value. This assumes that what is not defined (null) is the img2 object.
Actually I don't think your code should work at all, you are missing the. before the src So, try
document.getElementById("id1").src=json.img1.link;
document.getElementById("id2").src=json.img2.link;
document.getElementById("id3").src=json.img3.link;
and let us know if that doesn't solve the problem.
Btw, +points for learning JavaScript and not just straight into jQuery!

JavaScript will alert nodeValue, but when trying to display the text, it's null or causes errors

I have been having tremendous trouble getting this to work. There is no reason (to my knowledge) that this shouldn't work.
var xpath = '/course/module[#id=\''+modId+'\']/child::*';
var getData = sxe(xmldoc, xpath);
var result = getData.iterateNext();
The function returns the xpath. Just looks cleaner. This works 100%.
while (results)
{
var text = result.getElementsByTagName('title')[0].nodeValue;
document.write(text); // returns null
}
For the example, I use document.write, it returns null, but in my actual script, it usually says childNodes or whatever method I'm trying to access the data (I thought this would help) it never returns it. It causes an error and breaks it. When I use alert(), I get the exact text I want, everything works perfectly!
What is happening?!
try
var text = result.getElementsByTagName('title')[0].text; //concatenates the text of all descendant nodes
or
var text = result.getElementsByTagName('title')[0].firstChild.nodeValue;
I fixed it. Some of my XML data was missing a title attribute. This caused an error when trying to pass it to a variable, but alerting something that doesn't exist just ... doesn't alert it. So, it makes sense to why it works now.

Categories

Resources