如何在JavaScript中已经找到的div中获取特定类的元素? [英] How to get elements of specific class inside a div already found in JavaScript?

查看:88
本文介绍了如何在JavaScript中已经找到的div中获取特定类的元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要的是找到一个具有特定ID的div,然后在其中找到具有特定类的任何元素,并使它们中的第一个不可见。我已经尝试过

  var hostDivName = theHostDivName; 
var hostDiv = document.getElementsByName(hostDivName);
var theElements = hostDiv.getElementsByClassName( theClassDivName);
theElements [0] .style.display = none;

但在 hostDiv.getElementsByClassName( theClassDivName)上失败;

 对象#< NodeList>没有方法'getElementsByClassName'

错误。



<那么正确的方法是什么?我宁愿使用纯JavaScript(而不是jQuery等),只要看起来合理即可。

解决方案

如果是ID ,为什么要使用 getElementsByName 而不是 getElementById

  var hostDivName = theHostDivName; 

var hostDiv = document.getElementById(hostDivName);

var theElements = hostDiv.getElementsByClassName( theClassDivName);

theElements [0] .style.display = none;

假设您输入的是姓名,而不是ID

  var hostDiv = document.getElementsByName(hostDivName)[0]; 


What I need is to find a div with particular id, then find any element with particular class inside it and make the first of them invisible. I have tried

var hostDivName = "theHostDivName";
var hostDiv = document.getElementsByName(hostDivName);
var theElements = hostDiv.getElementsByClassName("theClassDivName");
theElements[0].style.display = "none";

But it fails on hostDiv.getElementsByClassName("theClassDivName"); with

Object #<NodeList> has no method 'getElementsByClassName'

error.

So what is the right way? I'd prefer using pure JavaScript (rather than jQuery or whatever) as far as this seems reasonable.

解决方案

If it's an ID, why are you using getElementsByName and not getElementById

var hostDivName = "theHostDivName";

var hostDiv = document.getElementById(hostDivName);

var theElements = hostDiv.getElementsByClassName("theClassDivName");

theElements[0].style.display = "none";

Assuming you meant name, and not ID

var hostDiv = document.getElementsByName(hostDivName)[0];

这篇关于如何在JavaScript中已经找到的div中获取特定类的元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆