简体   繁体   中英

DOM element and jquery object

if am accesssing any element by id using following code.

$("#container_svg_John_0")

it will return object that contains the element in index of "0". that is object of [0] will contains the element. i want to know in some cases finding other elements will gives the element directly (ie DOM element returned). what is the difference between those.

if am accessing the id of this it will return undefined.

$("#container_svg_John_0").id

but when i rewrites this like

$("#container_svg_John_0")[0].id

it will return the id of element. each and every time accessing like that above. how can i access the object which contains only single element in "0"th position instead of specifying [0]. and how it differs in other cases ?

$("#container_svg_John_0") is a jQuery object, which does have id property.

$("#container_svg_John_0")[0] returns the dom element, which has id property.

So basically the below is true :

$("#container_svg_John_0").attr('id') === $("#container_svg_John_0")[0].id

You are not using jquery object correctly - The correct way is :

$("#container_svg_John_0").attr('id');

This is DOM element $("#container_svg_John_0")[0] so it's valid to call

$("#container_svg_John_0")[0].id

If you to convert a jquery object to a DOM element, you can do as follows

var dom_elem = $("#container_svg_John_0").get(0);

alert(dom_elem.id);

If you want to access jQuery object's attribute, do

$("#container_svg_John_0").attr('id')
//or
$("#container_svg_John_0").attr('class') //etc etc

But you already have container_svg_John_0 inside $("#container_svg_John_0") selector :D

$("#container_svg_John_0") is a jQuery object thus you need to use attr() to get its id...

$("#container_svg_John_0").attr('id');

where as,

$("#container_svg_John_0")[0] returns the dom object, and hence you need to use [0].id to get the id of first element.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM