Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery Selector for dynamic id

Tags:

jquery

I am trying to change the image source in the Jquery

<a href="" class="wanted" id="'.$status_id[$num].'"><img src="/images/wanted.png">

through a JQuery selector:

$(".wanted "+ id).attr("src", '/images/wanted_.png');

Where id is defined in the javascript as the php variable $status_id[$num]. I first tried using $(this) to no avail. Any insight would be helpful.

like image 328
michael Avatar asked Jul 20 '12 03:07

michael


2 Answers

When you access $(".wanted"+id) , you are actually trying to access an element with the class name = wanted+id. This is because of the '.' before 'wanted'. Also, you seem to be accessing the <a> tag directly and setting it's src attribute. You need to access the <img> tag. What you could try is this:

var x=document.getElementById(id);
$(x).find("img")[0].setAttribute("src","/images/wanted_.png");
like image 50
karan k Avatar answered Nov 14 '22 09:11

karan k


ID of the HTML elements should be unique across the page.

You can try

//I assume id variable is already assigned the id of the element e.g var id = "<?php echo $status_id[$num] ?>";

$("#"+ id).attr("src", '/images/wanted_.png');

If you really want to select an element that has the given id and also the class wanted then try this:

$("#"+ id + ".wanted ").attr("src", '/images/wanted_.png');
like image 44
Chandu Avatar answered Nov 14 '22 08:11

Chandu