Create an HTML element to read it’s attributes in jQuery

Hi everyone! I am working on a WordPress plugin for embedding videos, and I came across needing to read an iframe’s attributes, before it is displayed anywhere. I searched on many forums, the jQuery documentation, and eventually found that you can create an element without it actually being present in the HTML! It’s frustratingly simple:

var element = $('<iframe width="420" height="315" src="http://www.youtube.com/embed/QSwilU0kJF0" frameborder="0" allowfullscreen></iframe>');

alert(element.attr('src')); // http://www.youtube.com/embed/QSwilU0kJF0
alert(element.attr('height')); // 315

Since $() is an object selector, you can also create the object on the spot, without it actually existing in the page! Cool, huh?

Leave a Reply

Your email address will not be published. Required fields are marked *