This will do it:
var obj = JSON.parse(json);
$('.giveMeHeaderList').append($('<div>' + obj.header + '</div>').find('ul.header'));
Pergunta
I am working with a JSON that contains chunks of HTML values. Below is a simplified version of the JSON to help you visualize:
{
"header" : "<a class='widget'>widget</a>
<a class='widget'>widget</a>
<ul class='header'>
<li>link1</li>
<li>link2</li>
<li>link3</li>
</ul>"
<a class='random'>random link</a>
<a class='random'>random link</a>,
"footer" : "<a class='social'>social</a>
<a class='social'>social</a>
<ul class='footer'>
<li>link1</li>
<li>link2</li>
<li>link3</li>
</ul>"
}
I'm having trouble finding a way to load the JSON, extract 'ul.header', and inject it into a div (using jQuery):
<div class="giveMeHeaderList"></div>
The end result should look like this:
<div class="giveMeHeaderLinks">
<ul class='header'>
<li>link1</li>
<li>link2</li>
<li>link3</li>
</ul>
</div>
(I apologize if the JSON is of incorrect format, as I typed it up quick and am only using it for display purposes)
Thanks for the help!
Solução
This will do it:
var obj = JSON.parse(json);
$('.giveMeHeaderList').append($('<div>' + obj.header + '</div>').find('ul.header'));
Outras dicas
The best solution is :
$.post("url/", {},
function (data/*({header: "<ul>...</ul>"})*/, textStatus) {
$("#giveMeHeaderLinks").html(data.header)
},
"json");
but, you need inject only part of header value, try this;
$.post("url/", {},
function (data, textStatus) {
$("#giveMeHeaderLinks").append($("<div>"+data.header+"</div>").find("ul.header"));
},
"json");
Assume you have this JSON:
htmltext = {"header": "<span><ul><a class='widget'>widget</a></ul></span>", "footer":"<a class='foot'>footer</a>"}
and you have the following html code:
<head>
<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
</head>
<body>
<div class="giveMeHeaderList">test</div>
</body>
Running the following JS will produce what you want:
$(".giveMeHeaderList").append($(htmltext.header).find('ul'));
using jQuery .find, to find the <ul>
element within the html and append it to the relevant .
htmltext is where your JSON sits, and header
is the relevant JSON element