问题描述
我需要从以下位置检索值的HTML代码段
Snippet of HTML code I need to retrieve values from:
<div class="elgg-foot">
<input type="hidden" value="41" name="guid">
<input class="elgg-button elgg-button-submit" type="submit" value="Save">
</div>
我需要获取值41,该值非常简单:
I need to get the value 41, which is simple enough with:
var x = document.getElementsByTagName("input")[0];
var y = x.attributes[1].value;
但是我需要确保我实际上是在"elgg-foot"内部检索值,因为HTML代码中有多个div类.
However I need to make sure I'm actually retrieving values from inside "elgg-foot", because there are multiple div classes in the HTML code.
我可以得到这样的课程:
I can get the class like this:
var a = document.getElementsByClassName("elgg-foot")[0];
然后我尝试以各种方式将其与 var x
组合在一起,但是我真的不知道这样做的语法/逻辑.例如:
And then I tried to combine it in various ways with var x
, but I don't really know the syntax/logic to do it.For example:
var full = a.getElementsByTagName("input")[0];
所以:从唯一类elg-foot内部检索值41.
So: Retrieve value 41 from inside unique class elg-foot.
我花了数小时在此搜索,但找不到解决方案(部分原因是我不确切知道要搜索什么)
I spent hours googling for this, but couldn't find a solution (partly because I don't know exactly what to search for)
谢谢大家的回答,它们似乎都可以奏效.我自己几乎可以正常工作,只是在原始代码中的某个地方忘记了 [0]
.同样欣赏JQuery,以前从未使用过它:-)
Thanks for the answers everyone, they all seem to work. I almost had it working myself, just forgot a [0]
somewhere in my original code. Appreciate the JQuery as well, never used it before :-)
推荐答案
最简单的方法是使用jQuery并使用CSS选择器:
The easiest way is to use jQuery and use CSS selectors:
$(.elgg-foot")确实总是会为您提供一个"elgg-foot"类的元素,但是如果您更进一步,则可以使用后代选择器:
$(".elgg-foot") will indeed always get you an element with class "elgg-foot", but if you go one step further, you can use descendent selectors:
$(".elgg-foot input[name='guid']").val()
这确保您仅获得名为guid的输入,该输入是标有elgg-foot类的元素的子代.
That ensures that you only get the input named guid that is a child of the element labelled with class elgg-foot.
现代浏览器中的等效方法是本机的querySelectorAll方法:
The equivalent in modern browsers is the native querySelectorAll method:
document.querySelectorAll(".elgg-foot input[name='guid']")
或者您可以做自己的事:
or you can do what you have yourself:
var x = document.getElementsByClassName("elgg-foot")
var y = x.getElementsByTagName("input")[0];
假设您知道它始终是div中的第一个输入
Assuming you know it is always the first input within the div
这篇关于Javascript-如何在特定的div类内从标签获取属性值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!