0

If we have a javascript object with html code like this:

var elm = "<div id="a"> <div id="b"> <div id="c"> </div> </div> </div>";

How can access #a via jquery?

for example $(elm).addClass('.red') doesn't work.

user3748973
  • 449
  • 2
  • 8
  • 24
  • 1
    http://api.jquery.com/jQuery/ - specifically "Return a collection of matched elements either found in the DOM based on passed argument(s) or *created by passing an HTML string.*" – jdphenix Mar 01 '15 at 18:16
  • 1
    Well your string is invalid. – epascarello Mar 01 '15 at 18:18
  • Never mind, I see what you did - escape double quotes inside your string or use single quotes to wrap it. – jdphenix Mar 01 '15 at 18:26

2 Answers2

2

for example $(elm).addClass('.red') doesn't work.

Except that it does.

var elm = '<div id="a"> <div id="b"> <div id="c"> </div> </div> </div>', 
    $elm = $(elm); 

$elm.addClass('red'); 
console.log($elm);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Output

Object { 0: <div#a.red>, length: 1 }

Edit:

Including my own comments here

Never mind, I see what you did - escape double quotes inside your string or use single quotes to wrap it.

Andreas Louv
  • 46,145
  • 13
  • 104
  • 123
jdphenix
  • 15,022
  • 3
  • 41
  • 74
  • I was just going to post that. That's the answer! If you need more detailed info, check this out http://stackoverflow.com/questions/3331449/jquery-remove-element-from-string/3331459#3331459 – Ryan Casas Mar 01 '15 at 18:31
2

First of all you should not use double-quotes inside of sourounding double quotes.

Change

 var elm = "<div id="a"> <div id="b"> <div id="c"> </div> </div> </div>";

to

var elm = '<div id="a"> <div id="b"> <div id="c"> </div> </div> </div>';

Now $(elm) will be the div with id #a. Only if you are searching for child elements of $(elm) you can find those with for example $(elm).find('#b') while $(elm).find('#a') will give you no result since #a is no child of itself.

L. Monty
  • 872
  • 9
  • 17