Using a JavaScript onclick function to retrieve specific elements within the document

I'm attempting to extract the elements from the source that was clicked on, but for some reason it's not functioning correctly.

Check out my JSFIDDLE

Here's the HTML:

<span class="populate" onclick="populate();" href="?id=1">Hello</span>

And here's the CSS:

.populate {
    cursor: pointer;
}

Followed by the JavaScript:

function populate(event) {
    var event = event || window.event;
    var src = event.srcElement;
    var href = src.getAttribute('href');
    alert(href);
}

I'm seeing an error in the console saying that the populate function is not defined.

If anyone has any suggestions or advice, I would greatly appreciate it!

Answer №1

The issue lies in the sequence of the javascript code and the placement of the span tag.

Make sure to include the javascript function before the span tag.

JS

    function populate(event) {
        var event = event || window.event;
        var src = event.srcElement;
        var href = src.getAttribute('href');
        alert(href);
    }

html

<span class="populate" onclick="populate();" href="?id=1">Hello</span>

It is important to define functions before invoking them. Check out the example on http://jsfiddle.net/HdvGD/7/

Answer №2

Your code executed successfully in the fiddle. The reason you were unable to get it working is because you wrapped it in onload() instead of using No wrap in Head (located at the top left corner of the fiddle).

View your fiddle1 here

If you prefer using onload(), you can assign it as a variable like this:

populate = function (event) {
    var event = event || window.event;
    var src = event.srcElement;
    var href = src.getAttribute('href');
    alert(href);
}

Feel free to check out another demo at fiddle2

For more insights, refer to this helpful answer that explains the difference

Update:

Apologies for mentioning the deprecated method (I have removed it). The event object "event" is not passed as a parameter. Here is a simpler approach - pass the event from onclick like this:

 onclick="populate(event);"

Then you can access it easily like so:

 function populate(event) {
    var src = event.target || event.srcElement;
    var href = src.getAttribute('href');
    alert(href);
}

View the updated version in Final Fiddle

Answer №3

Anchor tags typically have an href attribute

 <a class="populate" id="link" onclick="populate(this.id);" href="......">Hello
</a>



   function populate(id)
   {
       var someimage = document.getElementById(id);
       var mysrc = someimage .src;

   }

Answer №4

Try using jQuery to streamline the process

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>

     <script type="text/javascript">            

        $(document).ready(function() {
            $("#populate").click(function(event) {
                alert("Now you'll notice the link doesn't redirect to jquery.com");
                var href = $('#populate').attr('href');
                alert(href);
                event.preventDefault();
            });
        });

        </script>
</head>

<body>

<span class="populate" id="populate" onclick="populate();" href="?id=1" >Hello</span>
</body>
</html>

Answer №5

The code snippet you provided is functioning properly. To see it in action, navigate to the left-hand side and select the second drop-down menu. Change it to No Wrap - In <head>. Once done, your content should be displayed and the script will be loaded accordingly. Give it another try by visiting this link: http://jsfiddle.net/HdvGD/4/

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

JavaScript queries in Selenium WebDriver

Lately, I have been using the selenium webdriver (nodejs module) along with mocha for writing automation tests, and encountered a few challenges along the way. Issue with Scrolling driver.findElement() seems to return false as it is unable to find the e ...

Managing API calls through Next.js routing

Here is a next.js handler function for handling api requests on our server. I am looking for assistance on how to access a variable between request methods. Any help would be greatly appreciated. export default function handler(req, res) { if(req.met ...

Is it possible to validate a template-driven form without using the model-driven approach?

Attempting to validate a template-driven form in Angular without two-way data binding has proved to be challenging. I have successfully implemented validation using [(ngModel)], but running into an error when trying to validate the form without the MODEL p ...

What are some methods for utilizing the "name" attribute within React components?

About My Coding Environment Utilizing TypeScript and ReactJS The Issue with Using name as an Attribute Encountering the following error: Type '{ name: string; "data-id": string; "data-type": string; }' is not assignable to ...

Why is My TensorFlow.js Model for Predicting 2 Table Multiples Not Producing Accurate Results?

I have created a tensorflow.js model that predicts outputs in multiples of two. For example, if the input is 16, the prediction should be 32. However, even after providing the input data and labels accordingly, the output printed is [[1],] after prediction ...

Converting a variable with a cloned object from jQuery to vanilla JavaScript

const clonedBoardCode = $('#board_code').contents().clone(false); alert( clonedBoardCode.filter('div').eq(x).children().eq(y).text() );//need to fix this I am looking for a code similar to this $('#board_code_dup > div') ...

Alert: Github Dependabot has flagged Babel as vulnerable to arbitrary code execution when compiling meticulously designed malicious code

My Github Repository's Security section is flagging this issue as Critical for both my Frontend and Backend code. I'm having trouble grasping the nature of this alert. Can someone explain what flaw it represents? After updating my dependencies, ...

The function mysql_fetch_assoc is displaying absolutely nothing (neither null, nor 0, nor an empty string)

I'm encountering an issue with retrieving data from my $result variable. Everything works smoothly when there is one result, but if I try to check for a result and find none, the $array ends up empty. Running both commands below results in nothing bei ...

There seems to be an issue with the functionality of $apply in angular when used in conjunction with form

I've encountered an issue with my code where the form submission doesn't work properly unless I wait a few milliseconds before submitting. The problem seems to be related to setting the value of a hidden field called paymentToken. My goal is to ...

Convert time display to a 24-hour format using JavaScript

I managed to convert the time format from GMT to my browser's local time using the following JavaScript code: var newDate = new Date(timeFromat); timeFormat = newDate.toLocaleString(); Now, I want to change the time format to a 24-hour clock format ...

Guide to dynamically updating the href of an SVG Image in Angular HTML

I am currently iterating through a list of employee objects, each containing an image URL that I need to incorporate into an SVG - Image element. <div *ngFor ="emp of employees"> <defs> <pattern id = "attachedImage" height ...

"Converting an object to a JSON string using URLSearchParams: A step-by

I am currently working on a piece of code that retrieves all the input types from a form const form = document.querySelector('form'); const data = new URLSearchParams(new FormData(form).entries()); My main concern is how to convert the above ...

Is there a way to create a Vue.js component that retains the data I have added to it even when transitioning between routes? Currently, whenever I switch routes, the component deletes all the previously

I'm currently working on a webshop using Vue.js. When I add products, I utilize an event bus to pass the data to the CartComponent. Everything works as expected; however, if I navigate back or reload the page, all the data in my CartComponent gets del ...

Angular controller utilizing the `focusin` and `focusout` events from jQuery

Can anyone help me figure out why this piece of code is generating syntax errors in my AngularJS controller? $(".editRecur").focusin(function() { $(.recurBox).addClass("focus"); }).focusout(function() { $(.recurBox).removeClass("focus"); }); ...

Issues with Bootstrap 5 navbar-light and font style rendering on Edge browser

My website seems to be having compatibility issues with Microsoft Edge. While everything works fine on Chrome, the navbar classes "navbar-light" and "bg-light" do not apply properly in Edge, and the font style defaults. I am using Bootstrap 5 and webfonts ...

Enhance the aesthetics of placeholder text in Semantic UI React using CSS styling

Currently, I am utilizing Semantic UI dropdowns within my React application to generate drop-down menus similar to the ones showcased in their documentation found here: The initial text displayed is "Select Friend", and it appears with a semi-transparent ...

Using Vue.js to utilize a component within another component

I have a component that I would like to utilize within another component in order to create a navigation menu. I am looking to separate the menu from the links. How can I display data in a child component within another parent component while using Vue.js ...

What is the process for creating a modal transition?

I am attempting to add animation to a modal using a transition effect. My goal is to open it slowly, either from the center of the screen or from the bottom. However, I am struggling to understand how this can be achieved... While searching on Google, I c ...

What is preventing me from adding any style to this specific element?

Currently, I am in the process of creating a stopwatch for solving Rubik's cube. Within this project, there is a div element named "records" that is meant to display the time after a button is clicked. However, I am facing an issue where I am unable t ...

Scroll-triggered closing of modals in Next Js

I have integrated a Modal component into my Next.JS application, and I have implemented a functionality to close the modal when the user scrolls outside of it. However, this effect is also triggering when the user scrolls inside the modal. How can I modi ...