0

I have a javascript variable that contains a part of html code. I need to get in this part of html code a div html content. How can i do it ? This is an example:

var code = '<style type="text/css">
#example{
border:1px;
font-size:20px;
}
</style>
<div id="ex"> Some Content </div>
<div id="ex2"> Some Content <span> Another Content</span></div>
<div id="my_code">This Is My Code.</div><div id="ex3> Etc Etc </div>';

I'd like get content of div "my_code" with Jquery .html();

How can i do it ?

Thanks

5 Answers 5

1

code variable it's just a string for your document. If you have parsed this HTML code inside the body then you can use $('#my_code'), otherwise it's still just a string so.. that's another story.

Check the other story here: http://jsfiddle.net/NSCQh/1/

Sign up to request clarification or add additional context in comments.

Comments

0

I strongly suggest you have a look at jQuery's selector overview. They are the most important part of the jQuery magic, and without understanding them you'll get nowhere in the long run.

var html = $('#my_code').html()

or because that div containts text only

var txt = $('#my_code').text()

Comments

0

You've got a string, you need a DOM element. From that, you can get the jQuery object.

var el = document.createElement('div');
el.innerHTML = code;
console.log($(el));

Comments

0

pass the string to jquery and it works

var foo = '<div id="foo"> <span class="bar">fooBar</span> </div>';
var inside = $(foo).find('.bar').text();
alert(inside);

Comments

0

Create an ELEMENT, say p.

Use the following

$('<p>').append(code).find('div#my_code').html();

It create a p element, then append the content of variable code, then find div with id=my_code and select it's innerHTML.

Working model in the snippet.

var code = `<style type="text/css">
#example{
border:1px;
font-size:20px;
}
</style>
<div id="ex"> Some Content </div>
<div id="ex2"> Some Content <span> Another Content</span></div>
<div id="my_code">This Is My Code.</div><div id="ex3> Etc Etc </div>`;

var elm=$('<p>').append(code).find('div#my_code').html();

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

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.