v8rs
v8rs

Reputation: 307

JS DOM getAttribute()

I am trying to get an attribute value using the DOM and JS, but I can't make the code run. Why?

<!DOCTYPE html>
<HTML>
  <HEAD>
    <SCRIPT>

      var x = document.getElementById("sw").getAttribute("src");
      alert("src "+ x);

      document.getElementById("sw").innerHTML ="src "+ x;
    </SCRIPT>
  </HEAD>

  <BODY>
    <FORM>
      <IMG id="sw" src="photo.jpg"/>
    </FORM>
  </BODY>
</HTML>

Upvotes: 1

Views: 392

Answers (2)

Zakaria Acharki
Zakaria Acharki

Reputation: 67505

you're trying to get attribute of element that is not yet loaded try to put your js inside ready function so it will triggered just after the existence of DOM elements :

document.addEventListener('DOMContentLoaded', function() {
    var x = document.getElementById("sw").getAttribute("src");
    alert("src "+ x);

    document.getElementById("sw").innerHTML ="src "+ x;
});

Or you could place your <script> code right before the closing tag </body>.

Hope this helps.


<!DOCTYPE html>
<HTML>
  <HEAD>
    <SCRIPT>
      document.addEventListener('DOMContentLoaded', function() {
        var x = document.getElementById("sw").getAttribute("src");
        alert("src "+ x);

        document.getElementById("sw").innerHTML ="src "+ x;
      });
    </SCRIPT>
  </HEAD>

  <BODY>
    <FORM>
      <IMG id="sw" src="photo.jpg"/>
    </FORM>
  </BODY>
</HTML>

Upvotes: 1

shershen
shershen

Reputation: 9993

Tags of your HTML (DOM) is not yet loaded, not yet present at the moment when your JS code is executed. That's why you either need to move you below your HTML-code like so:

<!DOCTYPE html>
<HTML>
<HEAD>

</HEAD>

<BODY>
<FORM>
<IMG id="sw" src="photo.jpg"/>
<SCRIPT>

var x = document.getElementById("sw").getAttribute("src");
alert("src "+ x);

document.getElementById("sw").innerHTML ="src "+ x;
</SCRIPT>
</BODY>
</HTML>

or you need to add event handle on DOMLoaded event like so:

   <SCRIPT>
document.addEventListener("DOMContentLoaded", function(event) { 

    var x = document.getElementById("sw").getAttribute("src");
    alert("src "+ x);

    document.getElementById("sw").innerHTML ="src "+ x;
});
</SCRIPT>

Upvotes: 1

Related Questions