querySelector on custom elements won't work in external files - javascript

So I have this code:-
const extendCSS = (el1, el2) =>{
Array.prototype.slice.call(document.querySelector(el1).attributes).forEach(function(item) {
el2.setAttribute(item.name, item.value);
});
}
const build = (elementType) => tag => {
const query = document.querySelectorAll(tag);
query.forEach(ptag => {
const shadow = ptag.attachShadow({
mode: 'open'
});
const element = document.createElement(elementType);
element.innerHTML = ptag.innerHTML;
extendCSS(tag, element);
element.setAttribute('id', tag);
shadow.host.parentNode.replaceChild(element, shadow.host);
});
};
const h1 = build('h1');
const textarea = build('textarea');
textarea("text-editor");
h1("text-value");
const texteditor = document.querySelector('#text-editor');
const textvalue = document.querySelector('#text-value');
texteditor.addEventListener('keydown', ()=>{
textvalue.innerHTML = texteditor.value;
});
<text-editor></text-editor>
<text-value></text-value>
This build() does one thing:- it selects the custom element, changes its tag type and assign a id of name of the custom tag and replaces it with the desired thing. It is working fine here. but if I code all the thing after the build function in a external .js file and then bind it to the html and run it, but it won't work. How can I resolve this? This is a very important for now.
Help and answers appreciated. Thanks in advance.

Related

MathJax is not rendered. Dynamic ES6 import

I use MathJax to display formulas and more things in math. Like square root, limits, logarithm etc..
I have array of objects. Every object has 2 values. Question, Answer
/Objects/Matematika1.js
export const examples = [
{
question: "\\(ax^2 + bx +c = 0\\)",
answer: "(answer for 1)",
},
How app works:
In the menu i click something for example Math (Matematika1). Menu is standart <a href> with onClick function and ID. The function gets the ID and save it in localStorage
Menu Item
Matematika#1
I have a localStorage array but i need only ID as string.
let selectedPage = localStorage.getItem("page-value");
selectedPage.toString();
And then i need the value of selectedPage insert to import path. Object has same name as ID in menu item
//localStorage array to string variable
let selectedPage = localStorage.getItem("page-value");
selectedPage.toString();
//import { examples } from "./Objects/Matematika1.js";
//importing the array from /object/"selectedPage"
import("./Objects/" + selectedPage + ".js")
.then((array) => {
const { examples } = array;
//console.log(array);
function toggle(i) {
const div = document.querySelector(`#result_${i}`);
if (div.style.display !== "none") {
div.style.display = "none";
} else {
div.style.display = "block";
}
}
const container = document.querySelector("#examples-container");
examples.forEach((ex, i) => {
const card = document.createElement("div");
card.classList.add("card");
const example = document.createElement("div");
example.classList.add("example");
example.innerHTML = ex.question;
card.appendChild(example);
const button = document.createElement("button");
button.classList.add("toggle");
button.innerHTML = "Toggle";
button.addEventListener("click", () => toggle(i)); // Here is the event listener
card.appendChild(button);
const result = document.createElement("div");
result.id = "result_" + i;
result.style.display = "none";
result.classList.add("result");
result.innerHTML = ex.answer;
card.appendChild(result);
container.appendChild(card);
});
})
.catch((err) => {
console.log(err);
});
My issue is when i comment these lines and set static import path. MathJax render is working very well. But i need set import path dynamicly and in this case MathJax is not working.
import("./Objects/" + selectedPage + ".js")
.then((array) => {
const { examples } = array;
})
.catch((err) => {
console.log(err);
});
To be honest i have no idea what's wrong. The import("..").then().catch() i copied from this forum. In DOM i can't see any MathJax class so it look's JS don't have access to MathJax Library?
<div id="examples-container"></div> and also MathJax imported in index.html

How to append the child to the parent without using the ID element?

I used an ID to add a new element to divTwo. I want to know how to add the p tag inside divOne and divTwo without referring to their identifier. please help.
// create Tag
const createElement = (elementName) => document.createElement(elementName);
const appendTo = (idElement, element) => document.getElementById(idElement).append(element);
const setAttribute = (eleName, attribute, valueAttribute) => eleName.setAttribute(attribute, valueAttribute);
const setText = (id, text) => document.getElementById(id).innerHTML = text;
// Tag HTML
// div one
const divOne = createElement("div");
const appendDivOne = appendTo("demo", divOne)
const setIDOne = setAttribute(divOne, "id", "divOne");
// div two
const divTwo = createElement("div");
const appendDivTwo = appendTo("demo", divTwo)
const setIDTwo = setAttribute(divTwo, "id", "divTwo");
// child div two
const divTwoChild = createElement("p");
const appendDivTwoChild = appendTo("divTwo", divTwoChild);
const setIDChildeTwo = setAttribute(divTwoChild, "id", "ChildeTwo");
const text = setText("ChildeTwo", "childe two");
<div id="demo"></div>
It seems you are trying to append to div1 which, according to your code, will be the first element in . If you want to append a P tag, you can do:
const divOneChild = createElement("p")
const appendP = appendTo(document.getElementById("demo").firstChild, divOneChild)
You can access your elements directly after creation... for example when using const divTwoChild = createElement("p");, you can use divTwoChild.append() ... there is also a function called insertAdjacentHTML(), where you can add a html code directly on given position, read about in in here. Examples below (last 3 lines):
// create Tag
const createElement = (elementName) => document.createElement(elementName);
const appendTo = (idElement, element) => document.getElementById(idElement).append(element);
const setAttribute = (eleName, attribute, valueAttribute) => eleName.setAttribute(attribute, valueAttribute);
const setText = (id, text) => document.getElementById(id).innerHTML = text;
// Tag HTML
// div one
const divOne = createElement("div");
const appendDivOne = appendTo("demo", divOne)
const setIDOne = setAttribute(divOne, "id", "divOne");
// div two
const divTwo = createElement("div");
const appendDivTwo = appendTo("demo", divTwo)
const setIDTwo = setAttribute(divTwo, "id", "divTwo");
// child div two
const divTwoChild = createElement("p");
const appendDivTwoChild = appendTo("divTwo", divTwoChild);
const setIDChildeTwo = setAttribute(divTwoChild, "id", "ChildeTwo");
divTwoChild.append("childe two"); // <-- here
divOne.append('I am div one!'); // <-- or here
divTwo.insertAdjacentHTML('beforeend', '<p>I am a new p in div 2!</p>'); // <-- or here
<div id="demo"></div>

Javascript function to not load in images from a Http-source

I am new to Javascript and are trying to become better.
I was wondering how i can with the help och template-tag load the image in it if a Image is unsafe like from a http-source. Think of it like a email-client asking you if you want to load in images if not then it breaks the src. like src=temp-data, and when clicked to download and show the images then it sets the src to the correct one. here is the code i have written thus far
function removeUnsafeImgLinks(bodyContent) {
let _bodyContent = bodyContent
const el = document.createElement('template');
el.innerHTML = _bodyContent
const nodes = el.querySelectorAll('img[src^="http://"]');
if (nodes.length > 0) {
nodes.forEach((x => {
x.innerHTML.replace("src=temp-data")
}));
}
iframe.srcdoc = el.innerHTML;
return newBod;
}
Anyone got any tip or solution?
x.innerHTML.replace("src=temp-data") does not actually change anything
Fixing your syntax errors you might mean
const removeUnsafeImgLinks = bodyContent => {
const el = document.createElement('template');
el.innerHTML = bodyContent
const imgs = [...el.querySelectorAll('img[src^="http://"]')];
if (imgs.length>0) {
imgs.forEach(x => x.src='temp-data')
iframe.srcdoc = el.innerHTML;
}
};

How to get page language (hreflang) in JavaScript and add it as a parameter to a link

As an example, I have this code that is able to add the title of a page as a parameter to a link that is identified as an ID. I would like to be able to do the same for the language of the page. Thanks for your help!
<script>
const linkIds = [
'Your_link_id'
];
linkIds.forEach(id => {
const interval = setInterval(() => {
const link = document.querySelector('#' + id);
if (link) {
clearInterval(interval);
const href = link.getAttribute('href');
const pageTitle =
document
.title
.replace(/\s+/g, '_')
.replace(/&/g, '')
.toLowerCase()
const newHref = `${href}?your_parameter_name=${pageTitle}`;
link.setAttribute('href', newHref);
}
}, 20);
});
</script>
To get language of the page you have to get lang property from the document element. I created an example code which gets and sets the language of the page. You can save the output to some variable and create a link with it.
let lang = document.documentElement.lang
console.log(lang)
// output: en
document.documentElement.lang = 'af'
console.log(document.documentElement.lang)
// output: af
I added this as a new answer because I am not sure what I am suppose to do (this fact itself shows that this is not very well written question) but I will try.
So your script uses some array of IDs. Then it creates an interval for each ID that constantly updates the href attribute of element with that ID with some value. I don't know why would you do that as pageTitle or language is not changing over time but I might just stop asking so here is the edited code:
<script>
const linkIds = [
'Your_link_id'
];
// here I get the lanugage of the page
let lang = document.documentElement.lang;
linkIds.forEach(id => {
const interval = setInterval(() => {
const link = document.querySelector('#' + id);
if (link) {
clearInterval(interval);
const href = link.getAttribute('href');
// here I set the language where page title was before
const newHref = `${href}?your_parameter_name=${lang}`;
link.setAttribute('href', newHref);
}
}, 20);
});
</script>
Try it and report back. If you need to use such a complex script, it might do you good to actually learn Javascript.

how to select innerHTML from an elementHandle in puppeteer

Using the node puppeteer module, how do I continue with this code to get the innerContent here?
const els = Promise.all(await page.$$(selector)).then(results => {
results.map(async el => {
const tr = await el.$('tr')
//How do I convert this element handle to get its innerText content?
})
})
Like this
textValue = tr.getProperty('innerText').jsonValue()

Categories

Resources