ngopal
ngopal

Reputation: 219

How to select an particular image using javascript or css

How to select an particular image in table or <div> using javascript to get an id of image selected.

I want to save an image which is selected to an database according to username I think the above javascript is used to select the image but it is not working :

function imgWindow() {
   var s = window.getSelection()
   var r = document.createRange();
   r.selectNode(document.images[a, b, c]);
   s.addRange(r);
}
<div>
  <img src="images/p1.jpg" id="a" align="center" width="100" height="100" onclick="imgWindow()" />
  <img src="images/p2.jpg" id="b" align="center" width="100" height="100" onclick="imgWindow()" />
  <img src="images/p3.jpg" id="c" align="center" width="100" height="100" onclick="imgWindow()" />
  <img src="images/p2.jpg" alt="b" align="center" width="100" height="100" onclick="imgWindow() ">
</div>

`

Upvotes: 0

Views: 550

Answers (1)

asdf_enel_hak
asdf_enel_hak

Reputation: 7640

You can pass parameter image itself to imgWindow function then you can get id of image by prop()

function imgWindow(img) {
  //none juery version
  console.log(img.id)
  
  //jquery version
  console.log(($(img).prop("id")))
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <img src="images/p1.jpg" id="a" align="center" width="100" height="100" onclick="imgWindow(this)" />
  <img src="images/p2.jpg" id="b" align="center" width="100" height="100" onclick="imgWindow(this)" />
  <img src="images/p3.jpg" id="c" align="center" width="100" height="100" onclick="imgWindow(this)" />
  <img src="images/p2.jpg" alt="b" align="center" width="100" height="100" onclick="imgWindow(this) ">
</div>

Upvotes: 1

Related Questions