【问题标题】:How can I set <HTML> attribute without jQuery如何在没有 jQuery 的情况下设置 <HTML> 属性
【发布时间】:2019-07-21 10:45:16
【问题描述】:

我想在没有 jQuery 的情况下为标签设置属性。

我必须动态设置。

我知道在 jQuery 中你只是做 $('html') 但没有 jQuery,我试过 Document.getElementById('html') 但不起作用。

我该怎么做?

【问题讨论】:

  • 您的问题是设置属性还是选择正确的元素?请说清楚。

标签: javascript


【解决方案1】:

在一般情况下,等效于jQuery('element_name'); 的标准DOM 是document.getElementsByTagName('element_name');。请注意,它返回一个 NodeList(类似于数组)而不仅仅是一个 HTMLElementNode。

HTML 元素作为根元素,可以通过document.documentElement 访问。

可以通过HTMLElementNode 上的setAttribute('attribute_name', 'attribute_value'); 方法来设置属性值。该方法在旧版本的 Internet Explorer 中存在错误,因此您可能希望使用等效的 DOM 属性。

例如,替换class属性的值:

document.documentElement.className = "foo bar baz";

【讨论】:

  • 虽然document.documentElement 是等价的,但我认为document.getElementsByTagName('html')[0] 会更接近jQuery 的版本(但我还没有通过它的选择器引擎找到答案)。
【解决方案2】:
document.getElementsByTagName('html')[0].setAttribute('name','value');

【讨论】:

    猜你喜欢
    • 2014-01-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-01
    • 2011-11-30
    • 2018-04-15
    • 1970-01-01
    • 2022-10-07
    相关资源
    最近更新 更多