June 11, 2014

Creating DOM in jQuery

Document Object Model in HTML or XML is a well-formed document with HTML tags or XML elements.
With jQuery, we can create DOM using ‘createElement()’ method. Many times, while programming, there may situations arise when you have part of HTML in string format and need to query it to find a particular value of tag, defined in it. In such cases DOM plays a vital role to achieve it.
Mechanism is simple, first create a DOM object with HTML string and then find for the element in the DOM object. In jQuery, you can create DOM object as:

var dom = document.createElement('div');

While programming, I got trapped in a situation where I need to find ‘span’ tag value on click event of a ‘div’ element. The scenario was, it was bound with a nested ‘div’ and was returning complete element having multiple HTML tags and I had to find single value – Transaction Number, to display the corresponding detailed information. The same I am sharing here with you.




Now, you can easily find element from the above, using simple jQuery syntax.

var val = $(dom).find("span").text();

And the above code will return: ‘TRANS00007’ without worrying about to manipulate long string.

Hope, it will be useful for you somewhere.