views:

248

answers:

5

I'd like to be able to do:

if ($("cheese_tag") == document.getElementsByTag("cheese_tag")[0]){
alert("success!");
}

Is this possible? Basically what I'm wanting to do is use the ease and power of jQuery selectors to manipulate elements. Is what I'm talking about possible?

REVISION: Sorry, a better way to state my question would be "Can I convert jQuery objects to ones that normal javascript can manipulate?" as in get jQuery to return a javascript object for manipulation.

+10  A: 

When you find elements with jQuery, you can get them with the "get" function:

var regularElement = $('#myElementId').get(0);

Inside a ".each()" function, the "this" pointer refers to a "real" element:

$('input.special').each(function() {
  var type = this.type;
  this.value = "exploding balloon";
  // etc
})

Using jQuery doesn't make Javascript "different." It is Javascript, and the DOM is still the DOM.

Pointy
It took me a minute to understand why you were using the get() function on the jquery object, but then I read the comments on the question itself. It makes sense now. I can see get() being useful when integrating with non-jQuery JavaScript.
Wally Lawless
+1  A: 

$('myTag').get(0) returns the HTML element.

patrick dw
A: 

I assume you're trying to check if your jQuery object is the first instance of "cheese_tag". You can find the first tag with the :first selector and then you wouldn't need to do the comparison. For example, get the first div tag would be: $('div:first').

For the complete list of jQuery selectors, see the documentation.

wsanville
Not exactly...I wanted to get a javascript HTML element object as the return.
motionman95
A: 

Other people have already directly answered the question. Use the get() method.

However, most of the time you want to use jQuery methods to do the manipulation as opposed to getting access to the raw DOM element and then modifying it using "standard" JavaScript.

For example, with jQuery you can just say $('mySelector').addClass('myClass') to add a CSS class to a DOM element. This is much more complicated (and browser specific) using direct DOM manipulation. This concept extends to almost every other DOM manipulation you would care to do.

jkohlhepp
+2  A: 

jQuery uses the Sizzle Selector Engine*. You can use it on its own too.

* Confirmed by Doug Neiner, which means it's right ;)

Jonathan Sampson
Right! Simply include sizzle.js, then add this line: `window.$ = window.Sizzle`. And `$("cheese_tag")` will return `[<domelement>]`. `$("#cheese_id")[0] === document.getElementById("cheese_id")`
Doug Neiner
What, no "I'm Doug Neiner and I approve this answer"? Hehe.
Jonathan Sampson
I'm Doug Neiner and I approve this answer
Doug Neiner
Funniest thing I've read in a long time. Thanks Jonathan!
motionman95