Use css class/id from JSON key - javascript

I'm fairly new to JSON and the json file I'm working with has HTML elements in certain keys. Here's an example of data in an array I'm trying to pull.
"com" : "<p class=\"body-line ltr \"><span class=\"heading\">HEADING</span></p><p class=\"body-line ltr \">BODY</p>"
As expected, when it's pulled onto the page it's just displayed as text:
"<p class="body-line ltr "><span class="heading">HEADING</span></p><p class="body-line ltr ">BODY</p>"
How can I remove the HTML elements from the text and use them in my own web page? Keeping in mind that I can't actually edit the json file.
I'm using vue and vue resource.

Now that I know what you're asking --
You need to actually add the element to the DOM in order for it to show up as HTML on your page; until then, it is just a string.
There are many ways to do this, such as jQuery .append() if you use jQuery, or document.appendChild() if you have an object and want to use plain old JavaScript, or you can also set the innerHTML of an element using JavaScript to include the new contents.
I will provide one example here, using plain JS and innerHTML of a Div.
You get json from somewhere that looks like:
json = { "com" : "some HTML in here" }
You might have container some div like this on the page:
<div id="container"></div>
Then, wherever your JavaScript is, you could set the innerHTML of the container:
var containerDiv = document.getElementById("container")
containerDiv.innerHTML = json["com"]
This should give you enough direction to roll with this.
Here's my small example working in a jsFiddle:
https://jsfiddle.net/16pcayjq/

Related

Is it possible to edit the contents of a <script type="text/template"> with JavaScript?

Here's an example of what I'm trying to edit:
<script id="login-popup" type="text/template">
<h3 id="cover-msg" class="modal-title">You need to login to do that.</h3>`
</script>
I would like to add: class="title" to the h3 tag. This is being done via a chrome extension, so I can't control the HTML that is rendered.
Here's the caveat: I can't assume that the template will always be the same, so I can't just replace or edit the entire thing. I need to be able to select certain elements within the text and only add things as needed.
The problem I'm having is that the template seems to just be plain text. So I can't select it with something like #login-popup #cover-msg. Please correct me if I'm wrong.
Is it possible to do this with JavaScript/jQuery?
You can follow this type of procedure which gets the text out of the script tag, inserts it into a DOM element so you can use DOM manipulation on it, then gets the resulting HTML out of that DOM element. This allows you to avoid any manual parsing of the HTML text yourself:
var t = document.getElementById("login-popup");
var div = document.createElement("div");
div.innerHTML = t.innerHTML;
$(div).find("h3").addClass("title");
t.innerHTML = div.innerHTML;
It follows this process:
Get the innerHTML from the script tag
Create a temporary div
Puts the HTML into the temporary div where you can then treat it as DOM elements
Using DOM query, find the <h3>
Adds the class to it
Get the HTML back out of the temporary div
Puts the HTML back into the script tag as the modified version of the template.
It works here: http://jsfiddle.net/jfriend00/mqnf1mmp/.

Linking XML elements to page items in InDesign

I can check the XML of selected text like this:
app.selection[0].associatedXMLElements[0];
But in my research, I am still left scratching my head about how to do the most basic thing with XML using script: how do I assign XML to items? I can manually do this by opening the structure pane, then dragging the element over the desired frame on the page. If it's possible the old fashioned way, I imagine it's possible with script.
How do I link an existing XML element to an existing page item?
The above code only seems to work on selected text. If I select a graphic, it won't run.
How can I link XML to a selected graphic?
You can reference your xml node and your text frame and use placeXML
myXMl = myDoc.xmlElements[0];
var myXmlNode = myXMl.evaluateXPathExpression("/myXML/node1")[0];
var myFrame = app.activeDocument.pages[0].textFrames[0];
myXmlNode.placeXML(myFrame);
The advantage of this approach is that any aid:pstyle or aid:cstyle will be linked to existing matching style automaticaly
The alternative is to select the value of the node as text and place it into the text frame at insertion point:
myXMl = myDoc.xmlElements[0];
var myText = myXMl.xpath("/myXML/node1[1]/text()");
var myFrame = app.activeDocument.pages[0].textFrames[0];
myFrame.parentStory.insertionPoints[-1].contents = myText + '\r';
there are two specific properties. AssociatedXMLElement is for pageItems including textFrames and may be null if no tag is applied. AssociatedXMLElements only applies to text objects (characters, words…) because they can have several tags applied. Note that a non tagged text return an empty array and not null.
Associating tags to pageItems require that you first create or target existing xmlElements then use myInDesignObject.markup ( myXMLElement ).
EvaluateXPathExpression as Nicolai suggested is interesting once you want to browse through your XML structure. But it's sometimes quicker indeed to investigate associated XMLElement from the object rather than investigating the xml structure.
FWIW

Use callback function to create variables and use in a html element

Firstly excuse my ignorance with any inaccurate information I provide I a very new to javascript, jquery and json.
Anyway I have a script which pulls data from a json file and displays in a webpage with the help of javascript, jquery, ajax(i think) and json.
There is a callback for when I get back the results:
function searchCallback(data) {
$(document.body).append('<h1>' + data.title + '</h1>');
}
And it works fine the like this. However I want data.title (json object) to be displayed in a html element of my choice without having to use $(document.body) because my page won't display correctly at I have other html elements outside the script.
As far as I know (excuse ignorance) with javascript I can possible add a variable and use it as follows:
var title = data.title;
And in my html:
<span id="title"></span>
or maybe there is cleaner way?
Anyway how do I achieve this. Thank you for any help!!
If you want to find an element and modify, jQuery makes this easy. Instead of $(document.body).append find an existing element by it's id, and then call the text method on it to replace the text inside that element with something new.
$('#title').text(data.title);

Are HTML allowed inside HTML attributes?

For example, lets say you have something like this:
<div data-object="{'str': '<h1>This is a nice headline</h1>'}"></div>
Is this allowed in HTML5 and will it render properly in all browsers?
Edit:
With properly I mean that the browser will ignore and NOT render the H1 in any way ;)
Yes, it's allowed as long as it's quoted correctly.
Will it render? The H1 element? No - because it's not an element, it's just a bit of text inside an attribute of the div element.
Yes, browsers won't render any HTML tags inside attributes. This is pretty much common when you want to move the element later so it would show up. The only problem is that this is not a way to go as this does not create an element in DOM, thus, it will be much slower.
Try to find a way or ask for an alternative/better way to reuse the element which is hidden when the page is loaded.
Yes it's allowed and possible, but to make it work you have to make it valid JSON by using double quotes:
<div data-object='{"str": "<h1>This is a nice headline</h1>"}'></div>
Now to parse it just have: (jQuery will parse it to JSON all by itself)
var element = $("div").eq(0);
var rawData = element.data("object");
var rawHTML = rawData["str"];
$(rawHTML).appendTo("body");
Live test case.

How to optimize the creation of long html code to be used in javascript string

I need to define javascript variables containing very long html code.
Here is a short example:
var text = "Select one item:<br>";
text += "<ul class='thumbnails'><li class='span3'><a href='#' class='thumbnail'><img src='http://placehold.it/260x180' alt=''></a></li></ul>";
Since the html is going to be much much longer, I would rather work in pure html rather than append text to a javascript string.
I thought of creating a separate html file, but I guess that would require an Ajax call to fetch its content.
What is the best way to deal with this?
As N.Zakas said on "maintainable javascript" book, you should «keep html out of javascript» to promote high mantainability of the code through loose coupling of UI layers.
Beside the ajax solution you could also place the markup as a comment in the html file and read it via javascript (as a regular DOM node) or you could use some kind of microtemplating system (e.g. handlebars) and place your markup in a script block (the idea is to put markup where is expected to be found and not into javascript logic)
One possible solution is to use templates. There are a few JavaScript libraries that provide templating, underscore.js is one: http://underscorejs.org/#template, or more details on how to use it for templating http://www.headspring.com/blog/developer-deep-dive/an-underscore-templates-primer/
Plus underscore is great for a number of other things.
You could break up the text into actual HTML objects.
var thumbnailsUL = document.createElement('ul');
for (index in {your-thumbnails-list}) {
var thumbnail = document.createElement('li');
thumbnail.innerHTML = {whatever you need, more objects or html as text};
thumbnailsUL.appendChild(thumbnail);
}
Ideally though, there is no reason to build this IN JavaScript - can you not emit it from the server?
Instead of constructing HTML in Javascript as a string, I would rather suggest you to emit those html elements in the page itself and hide while loading. Then in Javascript, you could select that container and display it.

Categories

Resources