I am pretty new to JavaScript/web development in general. I am trying to create a JS function that takes an input string. That string will be the name of a class. I am trying to get all the elements of that class (they are all id's), and then add "OFF" to the end of all of the id's. I have been looking through existing threads, and found this one:
Give all elements in Class an seperate Id Javascript
However, I am still unable to get my function to work:
function idOFF (inputClass) {
var x = document.getElementsByClassName("'" + inputClass + "'");
for (i = 0; i < x.length; i++) {
x.setAttribute('id', x[i] + "OFF");
}
}
I have accomplished this on an individual level using jQuery, and tried incorporating that code into my function. It wouldn't work that way either:
function idOFF (inputClass) {
var x = document.getElementsByClassName("'" + inputClass + "'");
for (i = 0; i < x.length; i++) {
$("'#" + x[i] "'").attr("id", x[i] + "OFF");
}
}
If you're using jquery, you can do the following:
function idOFF (inputClass) {
var $elms = $("." + inputClass);
$elms.forEach(function () {
var $this = $(this);
$this.attr("id", $this.attr("id") + "OFF");
// or just this:
// this.id += "OFF"
});
}
You also can do that in pure javascript, fixing some issues you have in your current code:
function idOFF (inputClass) {
var x = document.getElementsByClassName(inputClass);
for (i = 0; i < x.length; i++) {
x[i].id += "OFF";
}
}
Note the getElementsByClassName
where I removed the additional quotes and I also removed the jQuery wrapping replacing it with id
.
function idOFF(inputClass) {
var x = document.getElementsByClassName(inputClass);
for (i = 0; i < x.length; i++) {
x[i].id += "OFF";
}
}
idOFF("foo");
#testOFF {
color: red;
}
<div class="foo" id="test">1</div>
<div class="foo" id="test1">2</div>
<div class="foo" id="test2">3</div>
<div class="foo" id="test3">4</div>
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments