Javascript 是否可以找到元素的父元素,然后在DOM中导航?

Javascript 是否可以找到元素的父元素,然后在DOM中导航?,javascript,jquery,Javascript,Jquery,使用jQuery时,如何返回到DOM导航。例如,如果我找到这样一个项的父项: $(this).parent() 你怎么能找到id为“foobar”的东西。 我试过: $(this).parent().$('foobar').addClass('hello') 但我得到的信息是: Uncaught TypeError: Object [object Object] has no method '$' 未捕获类型错误:对象[Object Object]没有方法“$”ID必须是唯一的,要按ID选择

使用jQuery时,如何返回到DOM导航。例如,如果我找到这样一个项的父项:

$(this).parent()
你怎么能找到id为“foobar”的东西。 我试过:

$(this).parent().$('foobar').addClass('hello')
但我得到的信息是:

Uncaught TypeError: Object [object Object] has no method '$'
未捕获类型错误:对象[Object Object]没有方法“$”ID必须是唯一的,要按ID选择元素,可以使用ID选择器
$(“#foobar”)
,但是如果要在父元素中查找元素,可以使用
查找
方法:

$(this).parent().find('#foobar').addClass('hello');
这与:

$('#foobar').addClass('hello');
请注意,如果对多个元素使用ID,则文档无效,应改用类

$(this).parent().find('.foobar').addClass('hello');

ID必须是唯一的,要按ID选择元素,可以使用ID选择器
$('#foobar')
,但是,如果要在父元素中查找元素,可以使用
查找
方法:

$(this).parent().find('#foobar').addClass('hello');
这与:

$('#foobar').addClass('hello');
请注意,如果对多个元素使用ID,则文档无效,应改用类

$(this).parent().find('.foobar').addClass('hello');

而id应该是唯一的,这样您就可以
document.getElementById(“foobar”)
我以前必须找到多个匹配项,并使用此项:

/* returns an array of all elements with id */
function getElementsById(id){
  var t=document.getElementsByTagName("*"),a=[]
  for(var i=0;i<t.length;i++)
    if(t[i].id==id)a[a.length]=t[i]
  return a
}
/*返回id为的所有元素的数组*/
函数getElementsById(id){
var t=document.getElementsByTagName(“*”),a=[]

对于(var i=0;iwhile id应该是唯一的,这样您就可以
document.getElementById(“foobar”)
我以前必须找到多个匹配项,并使用此项:

/* returns an array of all elements with id */
function getElementsById(id){
  var t=document.getElementsByTagName("*"),a=[]
  for(var i=0;i<t.length;i++)
    if(t[i].id==id)a[a.length]=t[i]
  return a
}
/*返回id为的所有元素的数组*/
函数getElementsById(id){
var t=document.getElementsByTagName(“*”),a=[]

对于(VARI=0;iOr仅$('#foobar').addClass('hello'));在这种情况下,答案或第一条注释都可以。一般来说,使用jQuery时,您必须先返回,停止,然后搜索。因此,上面的内容返回到父级,然后停止,并使用find方法从那里进行搜索。这两种方法都可以,但对于“id”来说,引用任何其他内容都没有意义。如果您使用的是“class”,则查找('.classname')将是更好的选择(显然,前提是元素包含在父元素中)。或者只是$('#foobar')。addClass('hello'));在这种情况下,答案或第一条注释都可以。一般来说,使用jQuery时,您必须先返回,停止,然后搜索。因此,上面的内容返回到父级,然后停止,并使用find方法从那里进行搜索。这两种方法都可以,但对于“id”来说,引用任何其他内容都没有意义。如果您使用的是“class”,则查找('.classname')将是更好的选择(显然,如果元素包含在父元素中)。