In 90% time I face a big problem. The "getElementById" problem. getElementById can use once ad It's connected with id and an id can declare once in html. On the contrary, class is good and can use many time. That's why I always wants to use querySelectorAll instead of getElementById. In my code, how can I replace id to class, so that I can use it as much I need.
let copyright_date = new Date();
let copyright_year = copyright_date.getFullYear();
document.getElementById("copyright-year").innerHTML = copyright_year;
document.getElementById("site-title").innerHTML = document.title;
<p>Copyright <span id="copyright-year"></span> - <a href="#" id="site-title"></a>.</p>
I want to change these id into class: id="copyright-year"
and id="site-title"
.
How can I do it using just javascript....?
CodePudding user response:
You can do it like this:
<p>Copyright <span ></span> - <a href="#" ></a>.</p>
<script type="text/javascript">
//$("#site-title").click(function(){location.reload()});
let copyright_date = new Date();
let copyright_year = copyright_date.getFullYear();
const copyright_elements = document.querySelectorAll(".copyright-year");
for (const element of copyright_elements){
element.innerHTML = copyright_year;
}
const site_title_elements = document.querySelectorAll(".site-title");
for (const element of site_title_elements){
element.innerHTML = document.title;
}
</script>
However, note that querySelectorAll
will not return a single element, but an array of elements. So, you have to know which element you want to access specifically.
CodePudding user response:
This is an attempt with as little code as possible:
[[".copyright-year",(new Date()).getFullYear()],
[".site-title",document.title]]
.forEach(([cls,val]) =>document.querySelectorAll(cls).forEach(el=>el.textContent=val));
<title>my articles</title>
<p>Copyright <span ></span> - <a href="#" ></a>.</p>
<p>Copyright <span ></span> - <a href="#" ></a>.</p>
Admittedly, this is probably a bit much for a Javascript newby. Therefore here are a few explanations
- The array structure
[[...]]
is an array of arrays: two arrays with two elements in it each, a className-based selector string and a value. - The value is in the first case the current year and in the second case the document's title.
- The loop with
.forEach(([cls,val])=>...)
over the outer array then uses an ES5 destructuring technique for assigning the elements of each sub-array to the local variablescls
andval
. - And, eventually, the inner loop with
document.querSelectorAll(cls).forEach(el=>...)
brings it all together: eachel
's.textContent
is set to the valueval
.