开发者

What's the best way to reference an element via ID in jQuery?

开发者 https://www.devze.com 2023-01-16 07:00 出处:网络
Should I be using $(\"#myElement开发者_开发技巧\") or $(myElement)? Both appear to work.EDIT: $(\'#myElement\') selects the element in the DOM which has an id of myElement, while $(myElement) expects

Should I be using $("#myElement开发者_开发技巧") or $(myElement)? Both appear to work.


EDIT: $('#myElement') selects the element in the DOM which has an id of myElement, while $(myElement) expects that the JavaScript identifier myElement be a DOMElement object or a string containing the selector.


You should use the jQuery selectors page as your reference.

There are a lot of selectors to choose from. Try out each one. Here's the two you reference in your question with 2 others:

$("#myElement")    // select and element with the ID "myElement"
$(myElement)       // use the variable myElement as your jQuery selector

$(document)        // The selector can also a DOM OBJECT
                   // document, window ...

$("body")          // To select a DOM element use this form

For example this will hide all the paragraphs on a page. Since the variable myElement is "p", $(myElement) will select all paragraphs on the page into a jQuery object.

var myElement = "p";
$(myElement).hide();

jsFiddle example


This will alert the visible width of the window:

alert($(window).width());

This will alert the contents of the DIV with an ID of myElement

alert($("#myElement").html());

All of this means that $("#myElement") will only select the same thing as $(myElement) if the variable myElement is "#myElement" or functions in an equivalent manner.

0

精彩评论

暂无评论...
验证码 换一张
取 消