Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting access to a jquery element that was just appended to the DOM

I am simply appending an element that is on the DOM like:

$("#div_element").append('<a href="#">test</a>'); 

Right after I append it I need access to the element I just made in order to bind an click function to it, I tried:

$("#div_element").append('<a href="#">test</a>').click(function(){alert("test")}); 

But the above didn't work. I could uniquely id the element but that seems like a bit to much work when perhaps there is a way I can get the element right after I append it.

like image 540
Greg Alexander Avatar asked Apr 19 '13 14:04

Greg Alexander


People also ask

Is it possible to access the underlying DOM element using jQuery?

The Document Object Model (DOM) elements are something like a DIV, HTML, BODY element on the HTML page. A jQuery Selector is used to select one or more HTML elements using jQuery. Mostly we use Selectors for accessing the DOM elements.

How do I grab an element from a DOM?

The easiest way to access a single element in the DOM is by its unique ID. You can get an element by ID with the getElementById() method of the document object. In the Console, get the element and assign it to the demoId variable. Logging demoId to the console will return our entire HTML element.

What is the difference between the append () and after () methods in jQuery?

. append() adds the parameter element inside the selector element's tag at the very end whereas the . after() adds the parameter element after the element's tag.


2 Answers

You can do this:

var el = $('<a href="#">test</a>');  $("#div_element").append(el);  el.click(function(){alert("test")});  // or preferrably: el.on('click', function(){alert("test")}); 

The append function accepts two types of arguments: a string or a jQuery element. In case a string is passed in, it will create a jQuery element internally and append it to the parent element.

In this case, you want access to the jQuery element yourself, so you can attach the event handler. So instead of passing in the string and let jQuery create an element, you have to create the element first and then pass it to the append-function.

After you've done that, you still have access to the jQuery element to be able to attach the handler.

like image 150
Kenneth Avatar answered Sep 20 '22 11:09

Kenneth


var $a = $('<a />', {href:"#"})   .text("test")   .on('click', function(e) {       alert('Hello')    })   .appendTo('#div_element'); 

http://jsfiddle.net/33jX4/

like image 25
RafH Avatar answered Sep 19 '22 11:09

RafH