【问题标题】:How add ID element to the specific class line?如何将 ID 元素添加到特定的类行?
【发布时间】:2017-01-11 10:45:58
【问题描述】:

我想在包含具有指定名称的类的行中添加一个 ID。例如。如果网站会屏蔽“div”或“li”,其中包含名称为“name-1 name-2 name-3”的类此函数检测到名为“name-1”的类并插入元素id="menu"该行看起来像这样:。你能帮我吗? 我试过了:

<div class="menu-item menu-item-object-custom menu-item-has-children">
I am a DIV or LI element
</div>

<button onclick="myFunction2()">Try it</button>

<script>
function myFunction2() {
    var x = document.getElementsByClassName("menu-item-has-children")[0];
        x.document.createElement("id");
}
</script>

【问题讨论】:

  • FWIW - 请注意不要将相同的 ID 添加到多个元素。

标签: javascript class add element


【解决方案1】:

你不需要document这是你需要的:

function myFunction2() {
    var x = document.getElementsByClassName("menu-item-has-children")[0];
        x.id="menu"
}

但是你应该研究一下 jQuery 来做这样的事情:

$('.menu-item-has-children').attr('id','menu')

使用 jQuery 所需要做的就是添加这个标签:

&lt;script src=https://code.jquery.com/jquery-1.11.3.min.js&gt;&lt;/script&gt; 到您的 HEAD 元素。


您可以通过了解选择器和 attr 来开始学习 jQuery。使用此链接:

【讨论】:

  • jQuery 更改 id?真的吗?
  • jQuery 通过类名获取并更改 ID。
  • @Aminadav 请注意,如果您没有带有 menu-item-has-children 类的 html 元素,您最终会出现错误:“Uncaught TypeError: Cannot set property 'id' of undefined”
【解决方案2】:

当您通过类名获取该元素时,使用以下方式为您的元素提供 id

<script>
function myFunction2() {
    var x = document.getElementsByClassName("menu-item-has-children")[0];
    $('.'+x).attr('id','menu');
}
</script>

【讨论】:

  • OP - 请注意这是使用 jQuery。对于 vanilla js,请查看@Aminadav 的答案。
【解决方案3】:

你可以使用Document.querySelectorAll():

function myFunction2() {  
  var elements = document.querySelectorAll('.menu-item-has-children');
  
  if (elements.length) {
    elements[0].id = 'menu';
  }
}
#menu {color:red;}
<div class="menu-item menu-item-object-custom menu-item-has-children">
  I am a DIV or LI element
</div>

<div class="menu-item menu-item-object-custom">
  I am another DIV or LI element
</div>

<button onclick="myFunction2()">Try it</button>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-02-20
    • 2015-11-08
    • 2016-02-15
    • 2023-03-16
    • 2018-11-23
    • 1970-01-01
    • 2023-03-15
    • 1970-01-01
    相关资源
    最近更新 更多