Reputation: 29598
$(document).ready(function(){
$("stack").each(function(){
styles = $(this).parse_attr();
$(this).convert_el().css(styles);
});
});
(function($){
$.fn.parse_attr = function(){
if(this.length === 0 ){
return null;
}
tag_types = ["class","id","name"];
css_hash = {};
$.each(this[0].attributes,function(){
attrib = this.name.split(":")
if( !($.inArray(attrib[0],tag_types) >= 0) ){
if($.isNumeric(attrib[1])){
css_hash[attrib[0]] = attrib[1] + "px";
}else{
css_hash[attrib[0]] = attrib[1];
}
}
});
return css_hash;
};
}(jQuery));
(function($){
$.fn.convert_el = function(){
if(this.length === 0 ){
return null;
}
klasses = this.prop("tagName").toLowerCase();
tag_types = ["class","id","name"];
$.each(this[0].attributes,function(){
attrib = this.name.split(":")
if($.inArray(attrib[0],tag_types) >= 0 ){
klasses = klasses + " " + attrib[1].replace(/"/g,"");
}
});
this.replaceWith($("<div class='"+ $.trim(klasses) + "'>" + this.html() + "</div>"));
return this;
}
}(jQuery));
If I do not iterate over the "stack" element it will apply the styles but for some reason it ignores .css(styles); during iteration. Any ideas?
Also please do not ask why I am trying to do things this way I am just experimenting with a conceptual idea of passing non existent html tags through jquery to dynamically develop a web page using things like
<stack class:center margin:100 color:red background-color:#FFF></stack>
It should then parse these values into a style and apply it.
Upvotes: 2
Views: 76
Reputation: 6244
I guess the problem is the replacing. The original element is removed, so you can't change its styles but $.fn.convert_el
still returns it.
Changing the function a little bit gives the desired result.
newDiv = $("<div class='"+ $.trim(klasses) + "'>" + this.html() + "</div>")
this.replaceWith(newDiv);
return newDiv;
Upvotes: 3