简体   繁体   中英

How to give unique html class name using javascript not from jquery

I am new in JavaScript, I want to search the number of id=heading and append unique class name to the existing class.

I have tried to do this using JavaScript but able to add only to the first heading only. Please refer the code-pen: https://codepen.io/restar312/pen/EqWOyV

var check_div = document.getElementsByTagName('div');
var numheading = 0;
for (var i = 0; i < check_div.length; i++) {
  if (check_div[i].id.indexOf('heading') != -1)
    numheading++;
  console.log(numheading);
  var d = document.getElementById("heading");
  d.className += numheading;
}

Expected class name should be class=First_heading1...class=First_heading2...class=First_heading3

The problem is that your heading have the same identical id heading . You should use different ids to access different DOM elements.

For example:

<div id="heading1" class=First_heading>
  <h1>Heading1</h1>
</div>
<div id="heading2" class=First_heading>
  <h1>Heading2</h1>
</div>
<div id="heading3" class=First_heading>
  <h1>Heading3</h1>
</div>

document.getElementById("heading")

Will always provide you with the first element having that id . Document.getElementById()

className s do not require to be unique, yet id s do. So you could loop through all div with that className and assign those an unique id instead.

 window.onload = function(){ for(var tListOfElements=document.querySelectorAll('.heading'), i=0, j=tListOfElements.length; i<j; i++){ tListOfElements[i].id = tListOfElements[i].id || 'heading_' + i; tListOfElements[i].textContent = tListOfElements[i].id } }; 
 <div class = 'heading'>A</div> <div class = 'heading'>B</div> <div class = 'noheading'>C</div> <div class = 'heading'>D</div> <div class = 'heading' id = 'wannakeepmyid'>E</div> 

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