简体   繁体   English

如何使用Javascript / JQuery将类和ID动态添加到特定标签

[英]How to dynamicly add class and id to specific tag using Javascript/JQuery

This is my html 这是我的HTML

<h1>Lorem Ipsum<h1>
<h2>Lorem Ipsum first h2<h2>
<h2>Lorem Ipsum second h2<h2>
<h2>Lorem Ipsum third h2<h2>

how to add class="sampleClass" to each h2 tag and give them id with increment number for each h2 tag using javascript/jquery? 如何添加class =“ sampleClass”到每个h2标签,并使用javascript / jquery为每个h2标签提供带有递增编号的id?

so i can get the folowing 所以我可以得到以下

<h1>Lorem Ipsum<h1>
<h2 class="sampleClass" id="0">Lorem Ipsum first h2<h2>
<h2 class="sampleClass" id="1">Lorem Ipsum second h2<h2>
<h2 class="sampleClass" id="2">Lorem Ipsum third h2<h2>

maybe i have to using loop but i cant do that yet :( 也许我必须使用循环,但我还不能做到这一点:(

Thanks 谢谢

No jQuery needed 无需jQuery

document.querySelectorAll('h2').forEach(function(el, i){
  el.id = i;
  el.classList.add('sampleClass');
});

1. First of all you need to be sure, that DOM content you are trying to access is available. 1.首先,您需要确保要尝试访问的DOM内容可用。

There are several techniques to do that in pure JS/HTML. 在纯JS / HTML中有几种技术可以做到这一点。 Read more here: 在这里阅读更多:

https://developer.mozilla.org/en-US/docs/Web/Events/DOMContentLoaded https://developer.mozilla.org/zh-CN/docs/Web/Events/DOMContentLoaded

and search more based on the page above. 并根据上面的页面搜索更多内容。

document.addEventListener("DOMContentLoaded", function(event) {
    const headers = document.getElementsByTagName("h2");

    Array.from(headers).forEach((header, index) => {
        header.classList.add("sampleClass")  
        header.setAttribute("id", index)
    })
});

2. Secondly, find elements you need on page using javascript document API. 2.其次,使用javascript文档API在页面上找到您需要的元素。

Since you want to find them by tag, use getElementsByTagName($tagNameHere) 由于getElementsByTagName($tagNameHere)标签查找它们,请使用getElementsByTagName($tagNameHere)

I've saved it into const variable just for redability, it s not necessary. 我已将其保存到const变量中只是为了实现可复制性,这不是必需的。

Outcome of getElementsByTagName($tagNameHere) will be HTMLCollection. getElementsByTagName($tagNameHere)将是HTMLCollection。 It seems to be Array or List of a sort, but it s not having methods, that you would expect from Collection in Javascript ( beware!! implementation of HTMLCollection differs based on browser - Welcome into Javascript in browser world :]). 它似乎是Array或List的一种,但是它没有Java的Collection中所期望的方法( 请注意 ,HTMLCollection的实现因浏览器而异-欢迎进入浏览器世界中的Javascript:])。

To iterate over HTMLCollection you can use several solutions. 要遍历HTMLCollection,可以使用几种解决方案。 Most intuitive for me it to cast it to Array, by using Array.from method which was introduced in ES6. 对我而言,最直观的方法是使用ES6中引入的Array.from方法将其转换为Array。

Also , 还有

as mentioned in @Aboalnaga answer you can just use querySelectorAll("h2") - another method to find collection of elements in document. 如@Aboalnaga答案中所述,您可以只使用querySelectorAll("h2") -在文档中查找元素集合的另一种方法。 This for change, will return collection that have forEach implemented for it (at least today, in Chrome) and you can iterate over it without casting. 对此进行更改,将返回为其实现了forEach集合(至少在今天的Chrome中如此),您可以在不进行强制转换的情况下对其进行迭代。

but

you can't really be sure this method will always be there in each browser (and you should generally care about your code behaving in the same manner in every browser you want to support) so probably better use casting with Array.from and dont worry about differences between browsers implementations. 您不能真正确定此方法是否会在每个浏览器中始终存在(并且通常应该关心您要支持的每个浏览器中代码的行为方式),因此最好使用Array.from ,不要担心关于浏览器实现之间的差异。

3. Add class you need to each element 3.将所需的类添加到每个元素

Since you are iterating, you will have access to HTMLElement inside loop. 由于要进行迭代,因此可以在循环内访问HTMLElement。 It has classList object available on it. 它具有classList对象。 That object holds API to manage classes of the element. 该对象拥有用于管理元素类的API。

header.classList.add("sampleClass")

4. Add ID to each element 4.为每个元素添加ID

You can use setAttribute method to do it. 您可以使用setAttribute方法来执行此操作。 header.setAttribute("id", index)

index comes from forEach loop. index来自forEach循环。 It is second argument of it. 这是它的第二个论点。

Also in your original question you have not closed your <h1> and <h2> tags!!. 同样在您最初的问题中,您还没有关闭<h1><h2>标签!! Closing tag syntax is </h2> . 结束标记的语法为</h2> Be careful and detailed when you code :). 在编码时要小心和详细:)。 Your mistake will create twice as many tags as you need, as browser will auto-close each open tag for you. 您的错误将创建所需标记的两倍,因为浏览器会自动为您关闭每个打开的标记。

Link to Codepen with solution: 与解决方案链接到Codepen:

https://codepen.io/anon/pen/wExLdM https://codepen.io/anon/pen/wExLdM

Relevant links: 相关链接:

For loop for HTMLCollection elements HTMLCollection元素的For循环

https://developer.mozilla.org/pl/docs/Web/API/Element/classList https://developer.mozilla.org/pl/docs/Web/API/Element/classList

http://clubmate.fi/javascript-adding-and-removing-class-names-from-elements/ http://clubmate.fi/javascript-adding-and-removing-class-names-from-elements/

For loop for HTMLCollection elements HTMLCollection元素的For循环

you can do task using below code using jquery 您可以使用jquery使用以下代码执行任务

$(document).ready(function () {
        $('h2').each(function (i) {
            $(this).addClass('sampleClass');
            $(this).attr("id", i);
        });

    });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在jQuery中向特定ID添加特定类 - How to add specific class to specific id in jquery 如何使用jQuery将ID添加到HTML标签 - how to add id to a html tag using jquery 如何在JavaScript或jquery中向类添加属性“ id”? - How to add attribute 'id' to a class in JavaScript or jquery? 通过javascript / jquery将class / id添加到带有特定文本的div中 - add class/id via javascript/jquery to div with specific text inside 添加带有Jquery或Javascript的类以进行<a>标记</a> - Add a class with Jquery or Javascript to <a> tag 标签中没有ID名称或特定类时,如何使用JavaScript将文本添加到HTML? - How to add text to HTML using javascript when there is no id name or particular class is present inside a tag? 如何使用jquery将特定类添加到锚标记的href等于URL? - How to add specific class to anchor tag has href equal to URL using jquery? 如何动态地将<strong>带有特定类</strong>的<strong>标签</strong>添加<strong>到</strong> <div> <strong>在JavaScript中</strong> - How to dynamically add a <strong> tag with a specific class to <div> in javascript 如何使用Jquery / Javascript添加和删除活动类以在li内锚定标签 - How to add and remove active class to anchor tag within li using Jquery/Javascript 如何使用 jQuery 添加动态递增的项目? - How to add dynamicly incrementing items with jQuery?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM