My code is like this
var tariffdate = PriceSheet.children('TariffEffDate')[1].text;
Where I expect to get data inside TariffEffDate tag. But it gives me undefined instead.
I can Get <TariffEffDate>1999-01-01T00:00:00</TariffEffDate> as a result for code
console.log(PriceSheet.children('TariffEffDate')[1])
But when I add .text to get data inside this node it is giving me undefined.
Can anyone point out what I am doing wrong here?
You need to use Node.nodeValue instead of .text.
.children('TariffEffDate')[1] will give you a HTMLElement that inherits Node, but it won't give you a leaf node, meaning that this HTMLElement might have multiple children. This is why you cannot get the value of (technically) multiple child-nodes. You can access the first node by calling Node.firstChild.
Essentially, you want your final code to be:
var tariffdate = PriceSheet.children('TariffEffDate')[1].firstChild.nodeValue;
Related
I have a table in which I want to extract the text of the active item. I do this with the following code:
var addedWorkout = $("#custDropDownMenuA").find(".dropdown-item.active");
console.log(addedWorkout);
addedWorkout = addedWorkout.textContent;
console.log(addedWorkout);
The problem is that I keep getting undefined. I checked the console and it indeed finds the element I want without fail.
I am relatively new to Javascript, but after over an hour of Googling I could not find the issue and I don't understand why. I know that I can get the text element if I hardcore it using the following line:
document.querySelector("#selectiona1").textContent
but not with:
$("#selectiona1").textContent
What is the difference between these 2? I read that textContent is part of the DOM, to my understanding it relates to objects and according to my console i think it is an object. I made some crazy attempts like putting the object I got into the querySelector, but nothing works.
With this line:
var addedWorkout = $("#custDropDownMenuA").find(".dropdown-item.active");
you're using jQuery to select the .dropdown-item.active inside #custDropDownMenuA, and when you select with jQuery, you get a jQuery object in response. So, addedWorkout is a jQuery object, and jQuery objects generally do not have the same properties/methods as standard HTMLElements. (querySelector is the vanilla Javascript method to retrieve an element)
Either select the [0]th item in the jQuery collection to get to the first matching element:
var addedWorkout = $("#custDropDownMenuA").find(".dropdown-item.active")[0];
Or use the jQuery method to get the text of the first matching element, which is .text():
var addedWorkoutText = addedWorkout.text();
(note the use of a new variable - you will likely find it easier to read and debug code when you create new variables rather than reassigning old ones, when possible)
Your var 'addedWorkout' is a Jquery object, not a html element.
To show the text use:
addedWorkout.text();
Alternatively, you can change the 'addedWorkout' to a html element by adding the index [0], like this:
addedWorkout[0].textContent;
I am currently trying to figure out a way to get the ID of an element, depending on whether its class contains something. I'm not sure if there's a better way to do it than I currently am, but having looked around nothing fits exactly the need I have. The code I currently have is, where I am looking for a div element whose class contains the string "one" but is not limited to that. Currently there is only one element containing this string but the alert provides me with [Object NodeList] (I may well be overcomplicating this):
$idToMove = document.querySelectorAll('div[class^="one"]');
alert($idToMove);
document.querySelectorAll() Returns a node list (kind of like an array), if you are sure there will only ever be one you have a couple options.
1) Use .querySelector instead:
// returns the first node that matches
var elm = document.querySelector('div[class~="one"]');
console.log(elm.id);
2) Access the first element in the returned list:
// returns all nodes that match
var elms = document.querySelectorAll('div[class~="one"]');
console.log(elms[0].id);
Make sure to null check returns of .querySelector and length check returns of .querySelectorAll.
Notice also, that I use ~= and not ^=. You can read on the MDN about the difference between all the equality operators. But for these two:
[attr~=value]
Represents an element with an attribute name of attr whose value is a whitespace-separated list of words, one of which is exactly "value".
[attr^=value]
Represents an element with an attribute name of attr and whose first value is prefixed by "value".
First get element from DOM and than from that element get id attribute:
1- If you need only first element then use querySelector like this:
let elms = document.querySelector('div[class~="one"]')[0].id
console.log(elms)
2- If you need all element those have this class then use querySelectorAll like this:
let elms = document.querySelectorAll('div[class~="one"]')
for(let i=0; i<elms.length; i++)
{
console.log(elms[i].id)
}
I think with "*" it works in more cases
document.querySelector('div[class*="words"]')
i tried it works absolutely amazing
window.frames[0].document.querySelector('td[id*="sss"]')
I have a function that requires a HTML element to perform the action on. I request the DOM selector as a parameter
function(document.body);
where element is the DOM query but somewhere else in the function I need the query as a string. Is it possible to turn the object into it's original string type? And if so, how?
You can do it the other way around. Pass your function a selector string:
functionName('body')
And then retrieve the relevant DOM element using .querySelector():
var el = document.querySelector(string);
The approach you are using is not going to produce the right results consistently in my opinion.
Passing in the element is going to mean that the element must be found beforehand and also is going to practically prevent finding other elements of similar location due to a lack of information.
Passing in a selector is an option, and then using that going forward if you need to find a similar set of elements but sometimes the selector is too complex to be placed in one string - for example if it needs filtering or some other metric.
Your best bet is to accept a callback function that returns the desired element or set of elements when you are dealing with complex selectors or locations for elements. It can simply return the same element each time if it is basic, or if it is more complicated the callback can access the DOM, filter based on some metric, and then return the subset which at times is ideal.
A callback function will provide the full amount of support without needing to always have a conversion to query string which is not always possible for complex structures.
If I understand you correct you could to this
function (elem) {
if (typeof elem === 'string' || elem instanceof String) {
elem = document.querySelector(elem);
}
var target = elem.querySelector(...);
}
To get the HTML string of an element use 'innerHTML'.
Temporary parent:
var div = document.createElement("div");
Append desired element to parent:
div.appendChild(document.body);
Test result:
alert(div.innerHTML);
If you are trying to get the string of the resulting element of 'querySelector()':
div.appendChild(document.body.querySelector('yourClass'));
The temporary parent ensures that you get the tags for the element returned. Otherwise you would only get the string for its child elements. If you want to use 'querySelectorAll()', just loop over the returned node array.
I am trying to get to a element (using javascript) which is inside UIAElementArray that has a number name like 1.
So when I try to get the element say with
array()["1"]
I am still getting the element at the index 1, instead of element which has a name/key value of 1.
Before some of you shoo me off to apple documentation, I found this and tried using firstWithName and withName
array().firstWithName("1")
but now I am getting a weird error "-[__NSCFNumber length]: unrecognized selector sent to instance 0x7c81ab0"
I haven't used length explicitly anywhere, what does the error mean and how do I get out of this?
I do not know exactly regarding the error but I know how to get required element. Try this one:
var predicate = "name contains '1'";
var requiredObj = mainWindow().popover().staticTexts().firstWithPredicate(predicate);
Hope this will help.
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.