I am trying to insert template literals that display the current date into two different HTML div elements. I am unsure of what rules I'm breaking, and cannot for the life of me find examples of this in my research.
The div elements I am trying to insert into have the classes 'headerDate' and 'footerDate'. Here is the JavaScript code I have written/ edited.
The template literals do not populate on my webpage at all. I know the script src is correct because a seperate function within the same JavaScript file works fine on my webpage. I also know that the div's have been implemented correctly because typing example text into the actual HTML of these two div elements displays the example text on the webpage.
const d = new Date();
const head = `Current Date: ${d}.`;
const foot = `Last Updated: ${d}.`;
const headerDate = document.querySelector('.headerDate');
const footerDate = document.querySelector('.footerDate');
headerDate.textContent = head;
footerDate.textContent = foot;
/* I have also tried inserting the template-literals this way, to no avail */
document.querySelector('.headerDate').textContent = head;
Related
I am new to this technology, and this is my first project.
I am calling an API and receiving a big parsed JSON file. From that entire big JSON.text (which is HTML code inside JSON.TEXT), how can I tap a particular class from that text?
Here is a sample:
After parsing the JSON.text - the outcome is -
some big html code then <table class ="info"> some big html code with TD and TR tag then </table> then again big HTML code.
I have to tap this table with class="info" from the entire parsed JSON.text which is HTML code.
screenshot -
Use DOMParser:
let response = {
parse: {
text: {
"*": `<div><\/div>
<p><\/p>
<table class="infobox vcard"><\/table>`
}
}
};
let parser = new DOMParser();
// extract the text part and pass it to the parser
let doc = parser.parseFromString(response.parse.text["*"], "text/html");
// get the first table element from the DOM, and display its `class` attribute
let tab = doc.querySelector("table");
console.log(tab.className); // infobox vcard
Once you've got the HTML out of your JSON file into a string you have two options. Option 1 is a regular expression:
// You have some string html
let match = html.match(/<table class="([^"])*"/)[1]
// match is the string "class1 class2" or whatever
match = match.split(" ")
// match is now an array ["class1", "class2"]
Option 2 is to find an HMTL parsing library (look one up), use it to parse the whole string, find the table using the output of that library, and extract its class that way.
I'm using Quill Editor, which is basically a Box like in SO where you type in text and get HTML out.
I store that HTML in a variable. Now my Website has a List of Tags (certain keywords) of brands and categories.
I would like a functionality to see if a Tag is inside that HTML.
For example, my Author types The new Nike Store is open now I would need the Nike to be a Tag. It can be a span with a certain class.
What is the best way to accomplish this? I want to check before publishing as live detection is not needed.
My Solution for now:
I didnĀ“t implement it yet, but I think I would try to check every word inside my tag list before going to the next and wrapping it in the needed HTML Tags if the word is a Tag. But this could get messy to code because of all the other stuff like the other HTML Tags that get generated through the editor.
Assuming that the author types just plain text, you can use a regular expression to search for tag words (or phrases) and replace the phrase in the HTML with that phrase, surrounded in a span with your new class:
const input = 'The new Nike Store is open now';
const htmlStr = input.replace(/\bnike\b/gi, `<span class="tag">$&</span>`);
document.body.appendChild(document.createElement('div')).innerHTML = htmlStr;
.tag {
background-color: yellow;
}
Or, for dynamic tags, create the pattern dynamically:
const input = 'The new Nike Store is open now';
const tags = ['nike', 'open'];
const pattern = new RegExp(tags.join('|'), 'gi');
const htmlStr = input.replace(pattern, `<span class="tag">$&</span>`);
document.body.appendChild(document.createElement('div')).innerHTML = htmlStr;
.tag {
background-color: yellow;
}
(if the tags can contain characters with a special meaning in a regular expression, escape them first before passing to new RegExp)
In the first example, the script was executed, but not in the second example, the Dom results are the same.
// executable
var c = 'alert("append a div in which there is a script element")';
var div = document.createElement('div');
var script_2 = document.createElement('script');
script_2.textContent = c;
div.appendChild(script_2);
document.body.appendChild(div);
// unexecutable although the dom result is same as above case
var d = '<script>alert("append a div that has script tag as innerHTML")';
var div_d = document.createElement('div');
div_d.innerHTML = d;
document.body.appendChild(div_d);
.innerHTML allows you to add as much HTML as you want in one easy call.
.appendChild allows you to add a single element (Or multiple elements if you append a DocumentFragment).
If you use .innerHTML then you need to include the opening and closing tags correctly. Your HTML must be proper.
When elements that were created using document.createElement then auto generate the appropriate opening and closing tags.
Your example for .innerHTML is not properly formed. Instead of:
var d = '<script>alert("append a div that has script tag as innerHTML")';
it should be:
var d = '<script>alert("append a div that has script tag as innerHTML")</script>';
UPDATE:
Interesting!!
I know that, in the past, your second example would have worked. But it seems that, probably for security reasons, the browser no longer allows you to insert <script> through .innerHTML.
I tried on Chrome 62 and it fails. Firefox 57 fails and Safari 11.0.2 fails.
My best guess is that this is a security update.
Look here:
https://developer.mozilla.org/en-US/docs/Web/API/Element/innerHTML
And go down to the Security considerations section.
It reads:
It is not uncommon to see innerHTML used to insert text in a web page. This comes with a security risk.
const name = "John";
// assuming 'el' is an HTML DOM element
el.innerHTML = name; // harmless in this case
// ...
name = "<script>alert('I am John in an annoying alert!')</script>";
el.innerHTML = name; // harmless in this case
Although this may look like a cross-site scripting attack, the result is harmless. HTML5 specifies that a tag inserted via innerHTML should not execute.
I'm practicing my Javascript by making a browser plugin to display external comment from Reddit on other webpages. The comments come in this format:
<div class="md"><p>I have them all over my yard. I didn't realize they spread so bad when I planted them.
They look cool with early morning dew on them though.</p>
</div>
I need to re-introduce the HTML characters (i.e. <div> => <div>), in order to put the formatted HTML onto the page.
Is there some native functionality Javascript provides to do this?
From what I can tell: x = document.createElement("div"); x.innerHTML = rawComment does not work, as the HTML is escaped, and the innerHTML returns a <div> with a string in it instead of a series of DOM nodes.
What you might try to do is the following:
// some dummy deocded text
let encoded = '<div class="md"><p>I have them all over my yard.</p></div>';
// create a new textarea and insert your encoded text
let dummyElement = document.createElement('textarea');
dummyElement.innerHTML = encoded;
// retrieve the textarea's value, which will be your decoded text
let decoded = dummyElement.value;
// decoded will be: <div class="md"><p>I have them all over my yard.</p></div>
Working Fiddle
This will work without jQuery, as you're only using the pure Javascript function's of your browser.
I'm working with XML files in InDesign CS6 that each have several dozen paragraphs where the attribute class="boxtitle". Each of these need to be set to the "Boxtitle" paragraph style. Because InDesign won't let you set styles based on attributes, my only options for assigning the correct styles to the relevant paragraphs is to do so manually, or via script.
Naturally, I chose the latter, and found a script on the Adobe forums that seemed like it would do the trick. Unfortunately, the script isn't working and I'm not sure why.
var myDoc = app.activeDocument;
//____________________ Apply Boxtitle
try{
var rootElement = myDoc.xmlElements.item(0);
var subheadElementList = rootElement.evaluateXPathExpression("Boxtitle");
for(i=subheadElementList.length-1; i>=0; i--){
var myAttribute = subheadElementList[i];
myAttribute.xmlContent.appliedParagraphStyle = myDoc.paragraphStyles.itemByName("boxtitle");
}
}catch(e){}
If anyone can point me to what's going wonky here, I'd appreciate it. Thanks!
you will want to use the correct xPath Expression to match your paragraphs
var subheadElementList = rootElement.evaluateXPathExpression("//*[#class = 'boxtitle']");
or more specific if your paragraphs have the markupTag name "mypara" for Example:
var subheadElementList = rootElement.evaluateXPathExpression("//mypara[#class = 'boxtitle']");