0

Kindly help.

JS

var x = document.querySelectorAll(".test1");

x.forEach(element => {
  element.removeAttribute("class",".test2");
  element.setAttribute("class",".test4");
});

Current HTML

<div class="clearfix">
<div class="clearfix test1 test2 test3">
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
</div>
<div class="clearfix test1 test2 test3">
    <div></div>
    <div></div>
    <div></div>
    </div>
</div>

Currently what the JS script does is removing the whole attribute class and its value and assigning/setting a new class with the new value.

I only want to modify 1 class name inside the attribute class

Current HTML Result

<div class="clearfix">
<div class="test4">
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
</div>
<div class="test4">
    <div></div>
    <div></div>
    <div></div>
    </div>
</div>

Desired HTML Result

<div class="clearfix">
<div class="clearfix test1 test4 test3">
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
</div>
<div class="clearfix test1 test4 test3">
    <div></div>
    <div></div>
    <div></div>
    </div>
</div>

I am just a newbie, i apologize if i naming them wrongly. Correct me if i am wrong. Thanksss.

2
  • 2
    use classList to deal with css class class list docs Commented Aug 14, 2020 at 9:38
  • 1
    Thank you @DavidNithaelTorresLima. This solved it > element.classList.replace("test2", "test4"); Commented Aug 14, 2020 at 9:44

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.