Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Manipulate DOM elements before adding them to the document [duplicate]

I was just wondering if there is a clean implementation to getting elements before appending them to the DOM.

Example (w/ jQuery):

var html = "<div class = 'test'><div class = 'innertest'>Hello!</div></div>";

var innerDiv = $(html).find('.innertest');

I feel like its not possible, but I'd like to see if there is any implementation out there that allows for this- because this would be pretty sweet for classes and separation.

EDIT: I'm wondering if this is possible. What I meant by clean was it didn't use like a string replace or something hacked up. It's not a situation where I make them. If I could make them I would just create variables as I go. I have a situation where I have this html string that I'd like to find elements from and manipulate BEFORE I append it to my page.

like image 285
Matt Avatar asked Oct 20 '25 16:10

Matt


2 Answers

This is how I ended up doing it:

var test = $("<div/>");
test.append(html);

test.find(".innertest");

// When I'm ready to append it..

$('#container').append(test);

I had to modify my HTML stream, but this ended up being a clean approach. Thanks for all your suggestions!

like image 85
Matt Avatar answered Oct 23 '25 07:10

Matt


var new_element = $(html);
new_element.find('.innertest').doStuffToIt(); //last one isn't an actual method

// and when you're done...

new_element.appendTo('#container');

You don't need to modify your HTML stream, because there's no need for the extra div.

I was looking for the same thing (that's how I got here) and after reading the solution you got to, I came up with this. And it worked great for what I needed.

like image 33
Stefan Matei Avatar answered Oct 23 '25 05:10

Stefan Matei



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!