15

How to get the element by its src attribute? I'm using:

<script type="text/javascript" src="mysrc.js?id=1000">

I would need to get that element on a variable. All I know is getAttribute("src") returns the src. If I knew anything else besides the actual src which is all I have. I can't use jQuery, just plain JS.

HoRn
  • 1,458
  • 5
  • 20
  • 25
lbennet
  • 1,083
  • 5
  • 14
  • 31
  • 17
    document.querySelector("script[src*='1000']") – dandavis Oct 08 '13 at 15:47
  • http://stackoverflow.com/a/9496574/886539 – Simon Arnold Oct 08 '13 at 15:48
  • 5
    just love the clowns who downvote this kind of questions – lbennet Oct 08 '13 at 15:49
  • You need to write your own method, see this a good reference [How to get the location (src) of a javascript file?](http://stackoverflow.com/questions/3548857/how-to-get-the-location-src-of-a-javascript-file) – Praveen Oct 08 '13 at 15:51
  • @dandavis asnwer works, but keep in mind it won't get script elemenements *below* executing code. Here http://jsfiddle.net/J6ZDf/ looking for `"script[src*='1000']` works, but looking for `"script[src*='2000']` doesn't. I think it would apply to any method. so you will have to place the code as the last code on the page. – Yuriy Galanter Oct 08 '13 at 15:55
  • it can be executed onload, in a timeout, or in conjunction with a domReady function. – dandavis Oct 08 '13 at 15:56
  • possible duplicate of [How do I get query string value from script path?](http://stackoverflow.com/questions/4716612/how-do-i-get-query-string-value-from-script-path) – bfavaretto Oct 08 '13 at 18:06

1 Answers1

4

You can do like this

<script id="mysrc" type="text/javascript" src="mysrc.js?id=1000">

var src = document.getElementById("mysrc").getAttribute("src")
console.log(src.split('id=')[1]); //1000
prakashapkota
  • 321
  • 2
  • 6