Dcoder February 2016

access element from javascript function to jquery function

var id=0;// globel 
var elem=0;// globel
$.fn.myFunction = function(element){
    var sid = element.getAttribute('href'); 
    elem=element;   
    id=sid;
};
$(document).ready(function(){

	$.fn.myFunction();
	alert(id);
	alert(elem);
});
<a href="#div-1" id="link-id-1" onclick="$.fn.myFunction(this);">Link 1</a><br>
<a href="#div-2" id="link-id-2" onclick="$.fn.myFunction(this);">Link 2</a><br>
<div id="div-1" class="hideAll">aaaaaaaaaaaaaaaaa</div><br>
<div id="div-2" class="hideAll">bbbbbbbbbbbbbbbbbb</div>

This code is not working I want to alert the id attributes "link-id-1" or "link-id-2" and href attributes "#id-1" or "#id-2" from the javascript function (myFunction()) to jquery function

Answers


Shubham Dubey February 2016

There is a basic error in your code. You are calling $.fn.myFunction on $(document).ready. It will not have a value for element.

Use this -

var id=0;// globel 
var elem=0;// globel
$.fn.myFunction = function(element){
var sid = element.href; 
elem=element;   
id=sid;
alert(id);
alert(elem);
};


abhay vyas February 2016

its better to use jquery simply rather than javascript for such kind of task

<!DOCTYPE html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
    <script>
    $(document).ready(function(){
        alert($("#link-id-1").attr("id")); 
        alert($("#link-id-2").attr("id"));
        alert($("#link-id-1").attr("href")); 
        alert($("#link-id-2").attr("href")); 
    });
    </script>
</head>
<body>
        <a href="#div-1" id="link-id-1">Link 1</a><br>
        <a href="#div-2" id="link-id-2">Link 2</a><br>
        <div id="div-1" class="hideAll">aaaaaaaaaaaaaaaaa</div><br>
        <div id="div-2" class="hideAll">bbbbbbbbbbbbbbbbbb</div>
</body>
</html>

Post Status

Asked in February 2016
Viewed 2,794 times
Voted 5
Answered 2 times

Search




Leave an answer