user3748973
user3748973

Reputation: 459

Access value of js object that has html

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.

Upvotes: 0

Views: 77

Answers (2)

L. Monty
L. Monty

Reputation: 882

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.

Upvotes: 2

jdphenix
jdphenix

Reputation: 15445

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.

Upvotes: 2

Related Questions