Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I target the content of a element, using JQuery?

I'm having trouble with a piece of code I'm using to build a widget. see below:

$(".number-plate").html(function(i, h) { 
   return h.replace(/(ANY|[A-Za-z0-9])/g, '<img src="plate-widget/$1.gif" />'); 
});

The problem is that this replaces the entire element, rather than just the content!

Is there a way of targetting the content of .number-plate ONLY?

Any help is Greatly Appreciated, Thanks

like image 268
Nasir Avatar asked Nov 30 '25 15:11

Nasir


2 Answers

You could extract the node, modify it and replace it afterwards, like this:

var html = $(".number-plate").html();
$(".number-plate").html(html.replace(/(ANY|[A-Za-z0-9])/g, '<img src="plate-widget/$1.gif" />'));
like image 175
Martin Jespersen Avatar answered Dec 03 '25 04:12

Martin Jespersen


(edit:) If you have more than one element with class number-plate, you can use:

$(".number-plate").each(function() {
   var $this = $(this);
   $this.html($this.html().replace(/(ANY|[A-Za-z0-9])/g, '<img src="plate-widget/$1.gif" />'); 
});
like image 42
Spiny Norman Avatar answered Dec 03 '25 03:12

Spiny Norman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!