Reputation: 261
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....?
Upvotes: 2
Views: 416
Reputation: 28236
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 class="copyright-year"></span> - <a href="#" class="site-title"></a>.</p>
<p>Copyright <span class="copyright-year"></span> - <a href="#" class="site-title"></a>.</p>
[[...]]
is an array of arrays: two arrays with two elements in it each, a className-based selector string and a value..forEach(([cls,val])=>...)
over the outer array then uses an ES5 destructuring technique for assigning the elements of each sub-array to the local variables cls
and val
.document.querSelectorAll(cls).forEach(el=>...)
brings it all together: each el
's .textContent
is set to the value val
.Upvotes: 1
Reputation: 20404
You can do it like this:
<p>Copyright <span class="copyright-year"></span> - <a href="#" class="site-title"></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.
Upvotes: 3