How to read this DOM object element elegantly without using jQuery find()? - javascript

I got some xml data, parsed it into a dom object so i can search and get values using jQuery.
Something like this:
<field>
<name>Jesus</name>
<group>God</group>
<blah>Hello World</blah>
</field>
In my js, I used an each() to loop through the field:
data.find('field').each(function() {
$(this).find("group").text();
}
I could use find() to fetch each field and content, but I don't want to use find as it could get expensive. I looked through the jQuery API i don't think i there is a function that could let me do something like "getElement('name')" or children('name') or next('name'), etc...
I don't want to use index either such as $(this)[0].childNodes[0] due to readability and potential future changes.
Any idea?

I'll give you an answer that doesn't use jQuery at all! How's that?
Your problem seems to be searching through the XML structure. So you converted it to a DOM tree, but now you're worried about the performance issues of traversing the tree.
The solution is simple: don't convert your XML to HTML, convert it to a JavaScript object literal, and work with that. It'll be the most simple AND the most efficient. For reference to convert XML to an object literal: XML to JavaScript Object
Now you are free to use all the tools JavaScript offers to work with your data, and you avoid any jQuery/DOM efficiency problems.

also try this
var xmlData = "<field><name>Jesus</name><group>God</group><blah>Hello World</blah></field>";
$(document).ready(function () {
var data = $.parseXML(xmlData);
$(data).each(function (i, node) {
alert($(node).text());
});
});

function alertit(jqueryObject) {
if (jqueryObject.length === 0) return;
jqueryObject.each(function() {
alert(this.nodeName.toLowerCase());
});
alertit(jqueryObject.children());
}
alertit($(xml));

Related

getElementsByTagName Equivalent in jQuery?

I need some help in converting a javascrpipt function into jQuery. Below is my original JS code:
var text = document.getElementsByTagName("pre")[0].innerHTML;
After a little research on Stack I was able to come up with this equivalent:
var text = $(data).$('pre')[0].html();
Where data is the data I receive in a $.get request, like below.
$.get (
mypage,
function parse(data) {
var raw = $(data).$('pre')[0].html();
}
);
But that doesn't seem to work and i'm not very good with jQuery.
Granted that data holds HTML, $(data).find('pre').eq(0).html() should do.
To get the first element with tag pre from data you can do the following in jQuery,
$('pre',data).eq(0).html();
http://api.jquery.com/jquery/#jQuery-selector-context
The reason $(data).$('pre')[0].html(); doesn't work is that the [0] part extracts the first found element as a DOM element, not a jQuery object, so invoking .html() fails.
Others have already pointed out the solution. .eq(0) gets the first element as a jQuery object (per moonwave99 and melc's answers), and that's why you can then call .html() on it.
For further reading on the difference, see: jQuery object and DOM element

Extracting values with Javascript

I have a variable called "result",
var result;
that result value is equal to following value, please presume that is just a string :)
---------result value -----------
for (;;);{
"send":1,
"payload":{
"config":{
"website":"",
"title":"welcome to site",
"website-module":1313508674538,
"manufatureid":"id.249530475080015",
"tableid":"id.272772962740259",
"adminid":100002741928612,
"offline":null,
"adminemail":"admin#website.com",
"adminame":"George",
"tags":"web:design:template",
"source":"source:design:web",
"sitelog":[],
"errorlog":0,
"RespondActionlog":0,
"map":null
},
"imgupload":""
},
"criticalerror":[0],
"report":true
}
---------result value------------
From that value, I would like to extract tableid which is "id.272772962740259" with classic Javascript.
How can I extract the code, please let me know how can i do with simple javascript, please don't use Jquery, all I just need is simple javascript.
You can simply evaluate the value of the variable to obtain the values. However, please note that your current value is not valid JSON; that for(;;); at the beginning of the value invalidates the format. Remove that, and you can do this:
var object = eval('(' + resultMinusThatForLoop + ')');
alert(object.payload.config.tableid);
If that data is a string the parse it with a JSON parse. The following should get the value you want
JSON.parse(result).payload.config.tableid; // "id.272772962740259"
Edit: though, as Tejs says, the for(;;) invalidates the string and stops it from being parsed. If you can remove that, do.
You need to remove the empty for loop, then parse the string. DO NOT use eval; most modern browsers provide built-in JSON-parsing facilities, but you can use json2.js if yours does not. Assuming that you assign the results of parsing the JSON to result, you should be able to get that value using result.payload.config.tableid.
You should probably read a good JS reference. JavaScript: The Good Parts or Eloquent JavaScript would be a good choice.
If result is a javascript object and not a string, you can just use 'result.payload.config.tableid'.
If it is not, how do you get the AJAX result? Are you using XmlHttpRequest directly? Most libraries will give you a javascript object, you might be missing a flag or not sending the response back with the right content type.
If it is a string and you want to parse it manually, you should use a JSON parser. Newer browsers have one built in as window.JSON, but there is open source code for parsing it as well.
var obj = JSON.parse(result);
alert('tableid is ' + obj.payload.config.tableid);

Reading Dynamic JSON Array

I trying to build a JavaScript function which will grab a JSON encoded array and return a value based on the requested key. I use the jQuery $.parseJSON() method to take the JSON string and convert it into a JavaScript object. Here a watered down example:
function getValue(dynamicArrayKey) {
var theArray = $.parseJSON(/* Get some JSON from a source using jQuery */);
alert('Here is the value: ' + theArray.dynamicArrayKey);
}
So the key I want will be given to the function, and it should return the resulting value. I am thinking that the JavaScript eval() method should be used in there somewhere, but I'm not sure. Any help would be greatly appreciated.
There's no need to eval(), use
alert('Here is the value: ' + theArray[dynamicArrayKey]);
Take a look at this. It may help.
How to search JSON tree with jQuery

Is it possible to get jquery objects from an html string thats not in the DOM?

For example in javascript code running on the page we have something like:
var data = '<html>\n <body>\n I want this text ...\n </body>\n</html>';
I'd like to use and at least know if its possible to get the text in the body of that html string without throwing the whole html string into the DOM and selecting from there.
First, it's a string:
var arbitrary = '<html><body>\nSomething<p>This</p>...</body></html>';
Now jQuery turns it into an unattached DOM fragment, applying its internal .clean() method to strip away things like the extra <html>, <body>, etc.
var $frag = $( arbitrary );
You can manipulate this with jQuery functions, even if it's still a fragment:
alert( $frag.filter('p').get() ); // says "<p>This</p>"
Or of course just get the text content as in your question:
alert( $frag.text() ); // includes "This" in my contrived example
// along with line breaks and other text, etc
You can also later attach the fragment to the DOM:
$('div#something_real').append( $frag );
Where possible, it's often a good strategy to do complicated manipulation on fragments while they're unattached, and then slip them into the "real" page when you're done.
The correct answer to this question, in this exact phrasing, is NO.
If you write something like var a = $("<div>test</div>"), jQuery will add that div to the DOM, and then construct a jQuery object around it.
If you want to do without bothering the DOM, you will have to parse it yourself. Regular expressions are your friend.
It would be easiest, I think, to put that into the DOM and get it from there, then remove it from the DOM again.
Jquery itself is full of tricks like this. It's adding all sorts off stuff into the DOM all the time, including when you build something using $('<p>some html</p>'). So if you went down that road you'd still effectively be placing stuff into the DOM then removing it again, temporarily, except that it'd be Jquery doing it.
John Resig (jQuery author) created a pure JS HTML parser that you might find useful. An example from that page:
var dom = HTMLtoDOM("<p>Data: <input disabled>");
dom.getElementsByTagName("body").length == 1
dom.getElementsByTagName("p").length == 1
Buuuut... This question contains a constraint that I think you need to be more critical of. Rather than working around a hard-coded HTML string in a JS variable, can you not reconsider why it's that way in the first place? WHAT is that hard-coded string used for?
If it's just sitting there in the script, re-write it as a proper object.
If it's the response from an AJAX call, there is a perfectly good jQuery AJAX API already there. (Added: although jQuery just returns it as a string without any ability to parse it, so I guess you're back to square one there.)
Before throwing it in the DOM that is just a plain string.
You can sure use REGEX.

JavaScript getElementsByCustomTag('value')?

I know getElementsByName('something') that returns the elements with name="something", but I want to return a list of elements where custom="something", how would I do that?
There are no standard API in the DOM to do this.
If you do not mind adding jQuery to your project, you could query your elements using the jQuery attribute selector:
$("[custom='something']")
To answer my own question, it seems it was easier than I thought.
elements = document.getElementsByTagName('pre');
for (elem = 0;elem < elements.length;elem++)
{
element = elements[elem];
if (element.lang != 'php')
break;
...
}
The above happened to work in my situation. :)
This page lists all the functions of the Document object in the JavaScript available in browsers. Thus it provides getElementById(), getElementByName() and getElementByTagName().
I guess need to use something like JQuery to gain more freedom as it allows you to express more complex "queries". I'm not sure, but that might also be slower, depending on how often you have to look up things.

Categories