简体   繁体   中英

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

This is my 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?

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

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.

There are several techniques to do that in pure JS/HTML. Read more here:

https://developer.mozilla.org/en-US/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.

Since you want to find them by tag, use getElementsByTagName($tagNameHere)

I've saved it into const variable just for redability, it s not necessary.

Outcome of getElementsByTagName($tagNameHere) will be 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 :]).

To iterate over HTMLCollection you can use several solutions. Most intuitive for me it to cast it to Array, by using Array.from method which was introduced in ES6.

Also ,

as mentioned in @Aboalnaga answer you can just use querySelectorAll("h2") - another method to find collection of elements in document. 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.

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.

3. Add class you need to each element

Since you are iterating, you will have access to HTMLElement inside loop. It has classList object available on it. That object holds API to manage classes of the element.

header.classList.add("sampleClass")

4. Add ID to each element

You can use setAttribute method to do it. header.setAttribute("id", index)

index comes from forEach loop. It is second argument of it.

Also in your original question you have not closed your <h1> and <h2> tags!!. Closing tag syntax is </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:

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

Relevant links:

For loop for HTMLCollection elements

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

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

For loop for HTMLCollection elements

you can do task using below code using jquery

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

    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM