Home > Software engineering >  getElementsByClassName plus a value filter of the data inside this element?
getElementsByClassName plus a value filter of the data inside this element?

Time:12-12

I need to add a filter to a function.

I have different elements in the page with the class a-text-center table-border, but I need the code working only if the element value is > 1, so other elements won't be affected by the script.

I can not add anything to the code, such as an ID or anything else to the element to differentiate it from the others, so the only way to differentiate it is using the value of the number inside this element.

Example of the element:

<td >4</td>

In this case the value is 4.

This is the script:

$(document).ready(function() {
  var x = (document).getElementsByClassName('a-text-center table-border');
  for (var i = 0; i < x.length; i  )
    x.item(i).className  = " bordertopred";

CodePudding user response:

Firstly, note that td elements do not have a value. What you're trying to read is the innerText of the element. This can be done using filter() after selecting the necessary elements from the DOM.

Also note that if you include jQuery in the page you may as well make use of it to do what you require. Below are two versions of the code, one utilising jQuery and the other plain JS.

First the plain JS:

document.addEventListener('DOMContentLoaded', () => {
  let valueToMatch = '4';
  let elements = Array.from(document.querySelectorAll('.a-text-center.table-border')).filter(el => el.innerText.trim() === valueToMatch);
  elements.forEach(el => el.classList.add("bordertopred"));
});
td {
  padding: 10px; 
}
.bordertopred {
  background-color: #CC0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<table>
  <tr>
    <td >1</td>
    <td >2</td>
    <td >3</td>
    <td >4</td>
  </tr>
</table>

This would be the jQuery equivalent:

jQuery($ => {
  let valueToMatch = '4';
  $('.a-text-center.table-border').filter((i, el) => el.innerText.trim() === valueToMatch).addClass('bordertopred');
});
td {
  padding: 10px; 
}
.bordertopred {
  background-color: #CC0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<table>
  <tr>
    <td >1</td>
    <td >2</td>
    <td >3</td>
    <td >4</td>
  </tr>
</table>

CodePudding user response:

I not understand. You can't add if statement at your function?

<script>
$(document).ready(function(){
    var x = (document).getElementsByClassName('a-text-center table-border');
for(var i = 0; i < x.length; i  ) {
   if (i > 1)
     x.item(i).className  = " bordertopred";
}
</script>

Also i would be inclined to use x.item(i).className.add('yourclass');

  • Related