javascript get element by function

Discussion in 'JavaScript' started by justin8831, Oct 23, 2015.

  1. #1
    <!doctype html>
    <html>
    <head>
    <script>
    function $(x) {
    return document .getElementByid (x);
    }
    </script>
    </head>

    <body>
    <div id=" div1"></div>
    <div id=" div2"></div>
    <div id=" div3"></div>
    <script> $("div1").innerHTML = "fuckkkk";
    </script>
    </body>
    </html>

    its supposed to say fuckkkkk right? what am I doing wrong
     
    justin8831, Oct 23, 2015 IP
  2. deathshadow

    deathshadow Acclaimed Member

    Messages:
    9,732
    Likes Received:
    1,999
    Best Answers:
    253
    Trophy Points:
    515
    #2
    Javascript is case sensitive, so you have to be bugger all careful you spell things right.

    In your case, you have document.getElementByid where it should be document.getElementById

    It's also a bad idea to start ID's with spaces in attributes, there was some legacy browser (forget which) that screwed those up. Same for extra spaces when calling the property of an object.

    <!doctype html><html lang="en"><head>
    
    <script>
    	function $(x) {
    		return document.getElementById(x);
    	}
    </script>
    
    </head><body>
    
    <div id="div1"></div>
    <div id="div2"></div>
    <div id="div3"></div>
    <script>
    	$('div1').innerHTML = 'fuckkkk';
    </script>
    
    </body></html>
    Code (markup):
    Works just fine. NOT that I'd ever use innerHTML since it's outdated and forces a slow reflow of the page, or that I'd have scripting in the markup unless absolutely necessary...

    But in terms of it working, 99% of your problem was saying "getElementByid" instead of "getElementById" -- simply typo.
     
    deathshadow, Oct 23, 2015 IP