Search code examples
javascriptjqueryonmousedown

Jquery returns undefined when trying to pull an element by its id with onmousedown


i have a javascript function that is going to change the text of the element in the font tag when i click it. I am trying to get the element by its id tag with jquery but when i console.log the jquery result it comes up as undefined. the all allWordsList variable is comming from python flask and i have confirmed that javascript is indeed receiving it properly the problem seems to be with this line var wordID = $(el).attr("id"); because it returns undefined when i console.log it

<script type="text/javascript">

    function changeText(el){
        var allWordsList = JSON.parse({{listFontsJ|tojson|safe}});
        console.log(allWordsList);
        var wordID = $(el).attr("id");
        console.log(wordID);
        var display = document.getElementById(wordID);
        display.innerHTML = '';
        display.innerHTML = allWordsList[wordID]["english"];

    }
  

</script>

<font id="1" size = '10' color = "red" onmousedown= "changeText()"> hello </font>


Solution

  • First, your code is using elements and attributes that are either deprecated (like font), no longer needed (like type=text/javascript) or legacy and not standard (like onmouseover).

    You should not be using HTML event attributes like onXyz and instead be separating your HTML from your JavaScript and do your event binding in JavaScript. And then, if the event handler is executing as a result of interacting with a DOM element, you can just use this to refer to the element that triggered the event.

    Also, it makes no sense to clear the innerHTML of the element and then on the very next line to set it. Just set it. But, really, you should avoid .innerHTML when you can (which is almost always) because it has security and performance implications. And you're not even setting the text to any HTML anyway. Instead, use .textContent.

    And, the font tag is deprecated. You should be setting the size and color of text with CSS and wrapping your text in valid elements, like div or span.

    Lastly, while and id that starts with a number is valid in HTML5, CSS won't recognize those ids. It's better to give your elements an id that starts with a letter and is meaningful. If you need a number to be associated with the element, it's better to use a data-* attribute.

    Here are all of those suggestions put together:

    #item1 { font-size:20px; color:red; }
    <div id="item1" data-index="1"> hello </div>
    
    <script>
        let allWordsList  = [ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul" ];
    
        document.getElementById("item1").addEventListener("mousedown", changeText);
    
        function changeText(){
           // Set the text to the data-index value of the HTML element:
           this.textContent = allWordsList[this.dataset.index];
        }
    </script>