1

Can we get the properties of HTML elements, with using there name or id, like following:

document.getElementById('id').value; //Javascript** 

$('#id').attr('class');  // jquery to get corresponding elements class**

And like these is there any way to get the specified event? In Html side I do this:

"<"input name='student' onclick='show()'">"

My need is, then how do we get which event is specified for input student?

3
  • Do you mean what the attribute contains, or which attributes are present ? Commented Jun 20, 2013 at 5:47
  • "<"input name='student' onclick='show()'">" Why did you put quotes like in your code? Is it string or what? This doesn't seem correct. Commented Jun 20, 2013 at 5:48
  • @adeneo : In a way similar to alert($('#id').attr('class')) which alerts the class , the OP wants to know the event handlers attached to the particular HTML element Commented Jun 20, 2013 at 5:50

2 Answers 2

1

Not sure I get it, but you can do something like

var el  = document.getElementById("id"),
    arr = [];

for (var i=0, attrs=el.attributes, l=attrs.length; i<l; i++){
    if (attrs.item(i).nodeName.indexOf('on') === 0) {
        var o = {};
        o[attrs.item(i).nodeName] = attrs.item(i).nodeValue;
        arr.push(o);
    }
}

this would get all inline event handlers attached to the element and put in an array looking like :

[{'onclick' : 'show()'}, {'onmouseenter' : 'javascript:void(0)'}]

etc...

FIDDLE

Sign up to request clarification or add additional context in comments.

Comments

1
var attrs = $('input').get(0).attributes;
var f = Array.prototype.filter.call(attrs, isEvent); //Filter all attributes
//f now contains all attribute nodes that are events
f.forEach(function(e) { console.log(e.nodeName); });    

function isEvent(element) {
    return element.nodeName.startsWith('on');
}

For the following input markup, it would log onclick, onchange. Works for events that are attached inline or event attributes created with JavaScript.

<input name='student' onclick='show()' onchange='return true;'/>

Or

var el = $('input').get(0);
el.setAttribute('onkeyup', function() {});
getEventsFor(el).forEach(function(e) {
    console.log(e.nodeName); //onSomeEvent
    console.log(e.nodeValue); // attached handler
});

function isEvent(element) {
    return element.nodeName.startsWith('on');
}

function getEventsFor(element) {
    var attrs = element.attributes;
    return Array.prototype.filter.call(attrs, isEvent);
}

JSFiddle

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.