-2

Can someone help me out. I'm attempting to createChrome extension that changes the div class on page load. Based on what I'm reading I would need to create a Javascript loop that changes the following div class:

Current: div class="article-holder article-holder--less"

Change: div class="article-holder article-holder--more"

If anyone can provide how to successfully accomplish this task, it would be much appreciated.

Nick
  • 16,066
  • 3
  • 16
  • 32

5 Answers5

0

You can assign a certain class to a DOM element using .className

e.g. myElement.className = "article-holder article-holder--more"

Please check the documentation: https://developer.mozilla.org/de/docs/Web/API/Element/className

0

You can remove the class from the element's list and add the new one in its place.

[...document.querySelectorAll('.article-holder--less')].forEach(e => {
  e.classList.remove('article-holder--less');
  e.classList.add('article-holder--more');
})
.article-holder--less { color: red; }
.article-holder--more { color: green; }
<div class="article-holder article-holder--less">Hello</div>
Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132
0

You will need to add an id to your div:

document.getElementById("MyElement").classList.remove('article-holder--less');

document.getElementById("MyElement").classList.add('article-holder--more');
<div id="MyElement" class="article-holder article-holder--less"></div>
-1

Basically, your extension should :

  • get all concerned tags with document.getElementsByClassName('article-holder--less')
  • loop on it : for each tag, do a div.className = div.className.replace('article-holder--less', 'article-holder--more')

Something like (not tested) :

var elms = document.getElementsByClassName('article-holder--less');
var div;
for (var i = 0; i< elms.length; i++) {
    div = elms[i];
    div.className = div.className.replace('article-holder--less', 'article-holder--more');
}
Pierre-Olivier Vares
  • 1,687
  • 15
  • 20
-2

You can use jquery for this.

     $( document ).ready(function() {
     $(".article-holder").attr("class", "article-holder article-holder-more");
     });
Rajan Sharma
  • 2,211
  • 3
  • 21
  • 33