I have a bunch of "a" elements on my page that hold the day of the month for a calendar. I have hidden labels, each containing a day of the month. I want to use JavaScript to check of there is a match. If there is a match, I want to add HTML nested within the a element.
Here is what I have tried, but it does not work as expected:
<span id="eventDayLabel1" class="daysClass">18</span>
<a href="javascript:__doPostBack('ctl00$MainContent$Calendar2','6317')" style="color:Black" title="April 18">18</a>
$(function () {
$('a').on('click', function (event) { event.preventDefault(); });
});
var elemAs = document.getElementsByTagName('a');
for (var i = 0; i < elemAs.length; i++) {
var elemA = elemAs[i];
var dayLabels = document.getElementsByTagName('daysClass');
function contains(dayLabels, elemA) {
for (var i = 0; i < dayLabels.length; i++) {
if (dayLabels[i].innerText == elemA.innerText) {
// add HTML here
}
}
return false;
}
}
Why doesn't this piece of code work? I've checked that the labels and a elements are being created there are matches (using inspect element in Chrome).
You aren't calling the contains()
function and you're using getElementsByTagName()
to get a class
.
Just remove the function and the return false
, and use getElementsByClassName()
instead.
var elemAs = document.getElementsByTagName("a"); for (var i = 0; i < elemAs.length; i++) { var elemA = elemAs[i]; var dayLabels = document.getElementsByClassName("daysClass"); //function contains(dayLabels, elemA) { for (var i = 0; i < dayLabels.length; i++) { if (dayLabels[i].innerText == elemA.innerText) { console.log('match'); } } //return false; //} }
<span id="eventDayLabel1" class="daysClass">18</span> <a href="javascript:__doPostBack('ctl00$MainContent$Calendar2','6317')" style="color:Black" title="April 18">18</a> <span id="eventDayLabel1" class="daysClass">18</span> <a href="javascript:__doPostBack('ctl00$MainContent$Calendar2','6317')" style="color:Black" title="April 18">17</a> <span id="eventDayLabel1" class="daysClass">19</span> <a href="javascript:__doPostBack('ctl00$MainContent$Calendar2','6317')" style="color:Black" title="April 18">19</a>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.