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
Related
I noticed something weird when using the uncompressed source of Dojo our code runs normally without error. I tried these two from the archives so far
dojo-release-1.10.6-src and dojo-release-1.10.8-src
However when I switch to the built versions, either
dojo-release-1.10.6 or dojo-release-1.10.8
There is an error that occurs when using dojo.query
TypeError: root.getElementsByTagName is not a function
My function call looks like this
var dom_frag = domConstruct.toDom(response);
var title = dojo.query(".accordion_title", dom_frag)[0];
where response contains HTML string. (too long to post here)
EDIT: Image of debugger showing contents of 'dom_frag'
Ok, have you checked to see if the dom_frag variable is a single dom node? If the dom fragment is multiple nodes, then the dojo.query won't work, because it needs to search the children of a single dom node.
To solve this, try wrapping the toDom contents with a single node... like so:
var dom_frag = domConstruct.toDom("<div>"+response+"</div>");
var title = dojo.query(".accordion_title", dom_frag)[0];
This is, of course, a bit of a hack... but if you can't guarantee that the response will end up a single node, then you need to do it.
Make sure your root is actually a DOM element as:
the Element.getElementsByTagName() method returns a live
HTMLCollection of elements with the given tag name. The subtree
underneath the specified element is searched, excluding the element
itself. Ref.
I have just started studying jquery and javascript and have encountered a line of code that I dont know how to translate. Any help would be much appreciated. Id like to translate it from JavaScript to jQuery so that I can use classes.
Here are the lines of code.
var rgb = getAverageRGB(document.getElementById('try'));
document.body.style.backgroundColor = 'rgb('+rgb.r+','+rgb.g+','+rgb.b+')';
You're mixing things up with that second line:
$('.post').css("background-color", 'rgb('+rgb.r+','+rgb.g+','+rgb.b+')');
And the jQuery way to find an element by its "id" value is
var rgb = getAverageRGB($('#try')[0]);
The $('#try') part creates a jQuery-wrapped list of nodes that match the selector, so in this case it'll be just one node. However, presuming that API expects a DOM node and not a jQuery wrapper, the trailing [0] extracts the raw DOM node from the jQuery wrapper.
Keep in mind that jQuery is JavaScript — we're not talking about two different languages.
I have started to convert a code on my site to jquery from mootols I would like to include jQuery instead of mootools and then write some functions I'm using in mootools to jQuery so I can use the exact same code. Some of the code I'm using I already converted is for example:
jQuery.fn.addEvent = jQuery.fn.bind;
However I'm having a hard time doing these:
$some_node.getElement('.class'); //where $some_node is an element like $(.selector);
$some_node.addClass('class');
$some_node.fireEvent('focus');
_node.setProperty('disabled', 'disabled').addClass('disabled');
$btn_node.removeProperty('disabled').removeClass('disabled');
Is there something out there for this?
Assuming the $some_node is a jQuery object, then the function equivalent in jQuery would be
getElement('selector') should be find('selector').first(), as getElement in Mootools seems to return the first element, thus first is used to reduce the find result array back down to one.
addClass('class') is just... addClass('class'). Can't see why you would have trouble with this.
fireEvent('event') should be trigger('event')
setProperty('attribute', 'value') should be attr('attribute', 'value')
removeProperty('attribute') should be removeAttr('attribute')
Of course there almost certainly are subtle differences between the functions in both languages, most of which I cannot point out as I am unfamiliar with Mootools.
Surely the above would convert to:
$('.class').addClass('class');
$('.class').live("focus", function(e) {
//Do something on focus
//E.g. $(this).attr('disabled', 'disabled').addClass('disabled');
});
Or if you just wish to set the document focus on that element:
$('.class').focus();
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.
I want to edit some HTML I get from a var I saved. like:
var testhtml = $('.agenda-rename').html();
console.log($('input',testhtml).attr('name'));
Also tried
console.log($(testhtml).find('input').attr('name'));
But i get undefined? I figured it'd work like an $.ajax, $.get, $.post? How else can i do it?
When you call .html(), you're only getting the content, not the .agenda-rename. So if the input is a direct child of .agenda-rename, then .find() won't be able to find it.
Probably better just to do without the .html() call:
var testhtml = $('.agenda-rename').clone(); // or .clone(true)
console.log($('input',testhtml).attr('name'));
Now you have the .agenda-rename element(s) and you'll be able to search for elements nested inside it/them.
EDIT: Based on comment, OP doesn't want to modify the original. As such, .clone() can be used. Answer above has been edited to reflect change.
If events are attached that should be retained, then you use .clone(true).
EDIT: The reason $('input',testhtml) and $(testhtml).find('input') give the same result is that they are actually the same thing.
jQuery converts the first version into the second behind the scenes. As such it is technically a little more efficient to use the second than the first.
Here's the code where jQuery makes the switch (after running a bunch of other tests to determine what it was passed).
http://github.com/jquery/jquery/blob/master/src/core.js#L150