0

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>

`

5
  • Possible duplicate of Get the image id using jquery Commented Mar 29, 2016 at 14:42
  • 1
    @MatthiasSteinbauer How is this a possible duplicate of that question? This question doesn't even have the jQuery tag. Commented Mar 29, 2016 at 14:53
  • In general the question is overly simplistic. It could easily have been answered by any of the aprox. 50 questions that the duplicate utility brought up. I don't believe that this particular question contributes much value to the community. Commented Mar 29, 2016 at 14:54
  • @MatthiasSteinbauer you really should have marked it as a duplicate of a more relevant question then. The question you flagged it against is jquery only. Commented Mar 29, 2016 at 15:01
  • 1
    Thanks for the feedback will do that in the future Commented Mar 29, 2016 at 15:03

1 Answer 1

1

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>

Sign up to request clarification or add additional context in comments.

1 Comment

He didnt say he was using jQuery

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.