Helios
Helios

Reputation: 23

Jquery click function use element as variable

I'm trying to create a script that will access the inner text of any clicked item with a class named "customclass". Note that this only targets a elements.

The problem is that the individual element that is clicked doesn't seem to be passed at all. The regular expression attached replaces spaces (if any) with underscores.

I've tried the following but none work as expected:

// (1)
$('a.customclass').on("click", function() {
  var inner = $(this).innerHTML.replace(/ /g, "_");
});

// (2)
$('a.customclass').on("click", function(e) {
  var inner = $(e.target).innerHTML.replace(/ /g, "_");
});

// (3)
$('a.customclass').click(function(e) {
  var inner = $(e.target).innerHTML.replace(/ /g, "_");
});

// (4)
$('a.customclass').click(function() {
  var inner = $(this).innerHTML.replace(/ /g, "_");
});

In every case the following error appears in the console:

Cannot read property 'replace' of undefined.

Can anyone see the issue? Thanks

Upvotes: 1

Views: 49

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337713

The problem is because jQuery objects do not have an innerHTML property.

To achieve what you need, either use the Element object provided from this directly:

$('a.customclass').on("click", function() {
  var inner = this.innerHTML.replace(/ /g, "_");
  console.log(inner);
});

Or alternatively, use jQuery's html() method:

$('a.customclass').on("click", function() {
  var inner = $(this).html.replace(/ /g, "_");
  console.log(inner);
});

I'd also suggest you have a quick read through the jQuery documentation, as even just a quick glance at the method names will give you a good idea of what they do, and what's possible.

Upvotes: 1

Related Questions