[英]How do you set an inline css style to an element using JavaScript?
I am trying to select an element by its "name" attribute and it's not working.我试图通过其“名称”属性选择一个元素,但它不起作用。 In the console I receive teh following error:
在控制台中,我收到以下错误:
VM777:1 Uncaught TypeError: Cannot read property 'tagName' of undefined VM777:1 未捕获的类型错误:无法读取未定义的属性“tagName”
My code is:我的代码是:
var test = document.getElementsByName("parameterstest")[0].tagName;
test.style.display='none';
Its seems like this code should work when I run it in the Chrome console.当我在 Chrome 控制台中运行这段代码时,它似乎应该可以工作。
When you write document.getElementsByName("parameterstest")[0].tagName;
当你写
document.getElementsByName("parameterstest")[0].tagName;
it returns you a string containing the tag name of that element.它返回一个包含该元素标签名称的字符串。 There is no way you can apply style property on that string.
您无法在该字符串上应用样式属性。 You can use style property on the element which is retrieved like this
document.getElementsByName("parameterstest")[0]
您可以在检索到的元素上使用 style 属性,就像这个
document.getElementsByName("parameterstest")[0]
So it should be所以应该是
var test = document.getElementsByName("parameterstest")[0];
test.style.display='none';
As people have pointed out, using .tagName
just returns the String of the tag name, like "TEXTAREA" or "DIV", and you can't set a style on a String.正如人们指出的那样,使用
.tagName
只会返回标签名称的字符串,例如“TEXTAREA”或“DIV”,并且您不能在字符串上设置样式。
What you seem to want to do is set a style on all the selected sorts of things, which you can do on each individual item.您似乎想要做的是为所有选定的事物设置样式,您可以在每个单独的项目上执行此操作。
document.getElementsByName("parameterstest")
will return an array of zero or more items. document.getElementsByName("parameterstest")
将返回零个或多个项目的数组。 For something like an <input type="text" name="...">
it's likely to be one item;对于诸如
<input type="text" name="...">
东西,它可能是一个项目; for <input type="radio" name="...">
it's likely to be several items.对于
<input type="radio" name="...">
它可能是几个项目。
Regardless of how many items are returned, you can apply something to all of them by using the .forEach
method of an Array.无论返回多少项,您都可以通过使用 Array 的
.forEach
方法对所有项应用某些内容。
document.getElementsByName('parameterstest')
.forEach(function(el) {
el.style.display = 'none';
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.