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
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/
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()
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));
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);
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>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.