-1

I tried using this statement:

$("td", calendar).getElementsByClassName("today")

but I kept getting the error that getElementsByClassName is not a function.

$("td", calendar)

gives back an array of "td"'s. Is it possible to access the "today" "td" only using one line, or is a some kind of iteration necessary?

Peter Cardenas
  • 508
  • 4
  • 13

2 Answers2

2

jQuery is a wrapper for DOM elements and has its own helper functions.

To filter a collection of elements, use .filter like so:

$( 'td', calendar ).filter( '.today' );

If you are only going to use tds with the today class, then it is better to alter your selector:

$( 'td.today', calendar );

You could achieve this with built in JS functions as well, like this

const tdCollection = document.querySelectorAll( 'td.today' );
console.log( tdCollection );
<table>
  <tr>
    <td>yesterday</td>
    <td class="today">today</td>
    <td>tomorrow</td>
  </tr>
</table>
lumio
  • 7,428
  • 4
  • 40
  • 56
  • I used your first suggestion, and it returned an array, so i just added a [0] and it was fixed, thanks. Do you know which method is faster? – Peter Cardenas Sep 21 '17 at 13:08
  • The last one without jQuery. jQuery itself is just a wrapper which of course relies on built in JS function. I wouldn't recommend using jQuery unless you really need to support older versions of IE - but as far as I know jQuery won't support older versions anyway. Nowadays pretty much everything can be easily done without jQuery. – lumio Sep 21 '17 at 13:11
0

You are mixing vanilla Javascript with jQuery.

Javascript

var x = document.getElementsByClassName("today")

this returns all elements with this classname in an array

jQuery

var x = $('.today');

when selecting an element with jquery you need to prepend a "#" for ids and a "." for classes

good luck and have fun learning javascript :)

[EDIT] Sorry, apparently I over read the real problem here. In your specific case you would best go with a solution similar to what @lumio suggested in his answer.

Apfelbox
  • 367
  • 4
  • 13
  • 1
    I can only imagine this got downvoted (not be me) because it didn't answer the specific case in the question. Maybe add a line and, "in your case, this means use..." – freedomn-m Sep 21 '17 at 11:44