Filip Górczyński
Filip Górczyński

Reputation: 765

Create HTML element object from HTML string in Prototype

I'm creating custom validation function used in Magento and there are passed 2 parameters to callback: v - value of field, element - element that is validated. My problem is that this HTML element is string and I can't use Prototype to create JavaScript object like when I use jQuery:

var element = '<input type="text" value="ABC" name="some_name" class="class1 class2" />';
console.log(jQuery(element));

How to get the same result with Prototype?

Upvotes: 2

Views: 1602

Answers (1)

Geek Num 88
Geek Num 88

Reputation: 5312

If you have a string that is HTML and want a HTMLElement object from it this will work

var element = '<input type="text" value="ABC" name="some_name" class="class1 class2" />';
var $element = new Element('div').update(element).down('input');
//change the down() method to the appropriate CSS selector

This is also helpful if you need to select specific elements out of a long string of HTML

var element = '<div id="div1"><input type="text" value="ABC" name="some_name" class="class1 class2" /></div><div id="div2"><span>Valuable text</span></div>';
var $element = new Element('div').update(element).down('div2 span');

Upvotes: 3

Related Questions