0

This is kinda hard to word so i'm hoping you understand it:

I have an entire page in a variable. I need to be able to do getElementsByClassName on it. But how?

I've tried:

$.get( base_url, function( data ) {
 var something = data.getElementsByClassName('.user_name');
});
3
  • how about data.getElementsByClassName('user_name'); no dot Commented Jul 21, 2014 at 8:59
  • what are the values of base_url and data? Commented Jul 21, 2014 at 8:59
  • Niang oh that might be it. I had user_name in a jQuery $() with the . to find classes. Let me try that real quick. Commented Jul 21, 2014 at 9:01

2 Answers 2

4

If your URL returns HTML, data is a string. Since you're using jQuery, you can have jQuery parse it for you:

var dom = $(data);

Then you can use all the usual jQuery methods on that disconnected set of elements, so:

var userNames = dom.find(".user_name");

If you weren't using jQuery, you could have the browser parse that into elements for you:

var div = document.createElement('div');
div.innerHTML = data;

...and then use use DOM methods on that disconnected div. I wouldn't use getElementsByClassName, though; querySelectorAll has better support; basically, it's in all modern browsers and also in IE8, but IE8 doesn't have getElementsByClassName.

var userNames = div.querySelectorAll(".user_name");
Sign up to request clarification or add additional context in comments.

7 Comments

@AaronDigulla: OMG do I need more coffee.
My guess is he's not aware of this fact ;-)
@TJ: Out of interest, how do browsers like injecting a complete HTML page (complete with doctype and <html> tags etc.) into a div`?) I'm not sure what the OP means with I have an entire page in a variable.
Well I don't need to put it in the page.
@Matt: They take the descendants of head and body and put them in the div. So for instance, if you do div.innerHTML = "<!doctype html><html><head><title>Foo</title></head><body><p>one</p><p>two</p></body></html>";, you'll end up with div.innerHTML being "<title>Foo</title><p>one</p><p>two</p>" or similar. Much better, if you're using jQuery, to use jQuery's more robust processing.
|
1

You are mixing pure javascript with JQuery

Try this

 data.getElementsByClassName('user_name');

instead of

 data.getElementsByClassName('.user_name');

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.