I'm not able to go through all children of an SVG file in JavaScript. I want to go through all the paths and perform a function on them(changing them to polygons).
I've tried creating an array of paths using querySelectorAll("path");, but it didn't work. Now I'm trying to sift through all the elements in the SVG file, converting paths as I go.
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Reader</title>
</head>
<body>
<input type="file" id="fileReader" />
<br>
<p id="Content"></p>
<script>
document.getElementById("fileReader").addEventListener('change',function(){
var fr = new FileReader();
fr.onload = function(){
console.log("File Loaded!")
}
parser = new DOMParser();
var doc = parser.parseFromString(fr.readAsText(this.files[0]), "text/xml");
console.log(doc);
var path = "path";
doc.querySelectorAll('*').forEach(function(){
if($(this).is(path)){
var polygon = doc.createElementNS("http://www.w3.org/2000/svg", "polygon");
polygon.setAttribute("id", $(this).getAttribute("id"));
console.log("Converting " + $(this).getAttribute("id"));
var len = $(this).getTotalLength();
var p = $(this).getPointAtLength(0);
var seg = $(this).getPathSegAtLength(0);
var stp=p.x+","+p.y;
for(var i=1; i<len; i++){
p=$(this).getPointAtLength(i);
if ($(this).getPathSegAtLength(i)>seg) {
stp=stp+" "+p.x+","+p.y;
seg = $(this).getPathSegAtLength(i);
}
}
polygon.setAttribute("points", stp);
$(this).replaceWith(polygon);
}
});
});
</script>
</body>
</html>
This gives me two errors:
XML Parsing Error: syntax error
Location: file:///C:/Users/Temp/Desktop/Experiment.html
Line Number 1, Column 1:.
ReferenceError: $ is not defined.
I've stopped trying to use doc.children() since it wasn't working.
Just add the jQuery library into your project.
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js">
CODE:
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<title>Reader</title>
</head>
<body>
<input type="file" id="fileReader" />
<br>
<p id="Content"></p>
<script>
document.getElementById("fileReader").addEventListener('change',function(){
var fr = new FileReader();
fr.onload = function(){
console.log("File Loaded!")
}
parser = new DOMParser();
var doc = parser.parseFromString(fr.readAsText(this.files[0]), "text/xml");
console.log(doc);
var path = "path";
doc.querySelectorAll('*').forEach(function(){
if($(this).is(path)){
var polygon = doc.createElementNS("http://www.w3.org/2000/svg", "polygon");
polygon.setAttribute("id", $(this).getAttribute("id"));
console.log("Converting " + $(this).getAttribute("id"));
var len = $(this).getTotalLength();
var p = $(this).getPointAtLength(0);
var seg = $(this).getPathSegAtLength(0);
var stp=p.x+","+p.y;
for(var i=1; i<len; i++){
p=$(this).getPointAtLength(i);
if ($(this).getPathSegAtLength(i)>seg) {
stp=stp+" "+p.x+","+p.y;
seg = $(this).getPathSegAtLength(i);
}
}
polygon.setAttribute("points", stp);
$(this).replaceWith(polygon);
}
});
});
</script>
</body>
</html>
Related
i want to open several tabs when someone clicks this button.but my current code just opens the first.by the way this is a repost since the previous 1 had a lot of typos that i corrected
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<button id="hi" type="submit" onclick="redirect()">button</button>
</body>
</html>
<script>
function redirect(){
var window1 = 'https://google.com';
window.open(window1, '_blank');
var window2 = "https://www.youtube.com/watch?v=dQw4w9WgXcQ"
window.open(window2, '_blank');
var window3 = "https://www.youtube.com/shorts/AlvXHz2pUL4"
window.open(window3, '_blank');
var window4 = "https://www.youtube.com/watch?v=J2GVKuYoIww"
window.open(window4, '_blank');
var window5 = "https://www.youtube.com/watch?v=1Z6CHioIn3s&list=RDMMYrJqDCaeSZg&index=20"
window.open(window5, '_blank');
var window6 = "https://www.youtube.com/watch?v=KbNL9ZyB49c&list=RDKbNL9ZyB49c&start_radio=1&rv=KbNL9ZyB49c&t=32&t=32"
window.open(window6, '_blank');
var window7 = "https://www.youtube.com/watch?v=fB8TyLTD7EE&list=RDKbNL9ZyB49c&index=3"
window.open(window7, '_blank');
var window8 = "https://www.youtube.com/watch?v=Zasx9hjo4WY&list=RDKbNL9ZyB49c&index=8"
window.open(window8, '_blank');
var window9 = "https://www.youtube.com/watch?v=r6zIGXun57U&list=RDKbNL9ZyB49c&index=7"
window.open(window9, '_blank');
var window10 = "https://www.youtube.com/watch?v=v7HAVTyvLqI&list=RDKbNL9ZyB49c&index=8"
window.open(window10,'_blank');
}
</script>
I'm trying to display all elements of an array, by iterating through the arrray, but after I chose the file (from the input), the element in page changes to : "unidentified". Why?
function getElement() {
console.log('sfgsdf')
document.getElementById('files').onchange = function() {
console.log('sfgsdf')
let file = this.files[0];
let reader = new FileReader();
reader.readAsText(file);
reader.onload = function() {
variableIs = this.result
function sleep (time) {
return new Promise((resolve) => setTimeout(resolve, time));
}
function display(asd) {
const usingSplit = asd.split(' ')
lengthOf = usingSplit.length
for (var i = 0;i < lengthOf;i++) {
sleep(1000).then(() => {
document.getElementById('test').innerHTML = usingSplit[i];
});
}
}
display(variableIs);
}
}
}
getElement()
The HTML code is just this simple one :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1 id="test">TEST</h1>
<script src="test4.js"></script>
</body>
</html>
The problem is the var inside the for loop.
You should use let instead due to the way both work.
Read this post to understand their difference:
What is the difference between "let" and "var"?
The way you're using the sleep function is not gonna work since they will execute at the same time.
You can solve this by using async await.
function delay(ms = 0) {
return new Promise(resolve => setTimeout(resolve, ms))
}
const inputFile = document.getElementById('files')
const test = document.getElementById('test')
function init() {
inputFile.onchange = async function() {
const file = this.files[0];
const content = await file.text()
const splitText = content.split(' ')
for (let i = 0; i < splitText.length; i++) {
test.innerHTML = splitText[i]
// Here we are actually waiting in the for loop since this is an async function
await delay(1000)
}
}
}
init()
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1 id="test">TEST</h1>
<input id="files" type="file">
</body>
</html>
I would like create one div on body, any time i send a request post to my localhost. But he return all time "document is not defined", someone can help me?
app.post('/tshirt/:id', (req, res) => {
url.push(req.body.Musica);
User.push(req.body.User);
for (let index = 0; index < url.length; ++index) {
let elemento = document.createElement("div");
let padre = document.body("sendMusics");
let referencia = document.getElementById("dsmuix")[index];
elemento.innerHTML='<div id="dsmuix" style="background-color:blue; width:97%; height: 75px;margin-top: 1px;margin-left: 2%;width: 50%;height: 100%;float: left;" ><label style="margin-top:15px;display:inline-block;margin-left: 5%;">'+url[index]+'(time)<br><br> '+User[index]+'</label></div>';
padre.insertBefore(elemento, referencia);
}});
Can help me? Thanks
Use something like this
const createElement = () =>{
const newDiv = document.createElement("div");
newDiv.innerHTML = 'it works'
document.body.appendChild(newDiv)
}
document.body.onload = createElement
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
</body>
</html>
I'm currently creating a dashboard and I want to create a "Bootstrap List Group" which should show a list of friends of the current dashboard.
I have given to arrays like this:
friendsID[id1, id2, id3]
friendsName[name1, name2, name3]
I want to create a method in javascript so that the result looks like this.
<div class="list-group">
name1
name2
name3
</div>
Would love to here how you would manage this because I am a little bit desperate and have no clue how to do this.
Here You can use document.write() to solve the problem it is used when the path for the html is not needed
var friendsID = ['id1','id2','id3'];
var i=0;
var friendName = ['name1','name2','name3'];
console.log(friendName[2]);
idplace();
function idplace(){
for(i=0;i<friendsID.length;i++)
{
document.write("<a href='/dashboard/"+friendsID[i]+"' class='list-group-item list-group-item-action'>"+friendName[i]+"</a><br>")
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<script src="./java.js"></script>
</body>
</html>
Or You can Use Innerhtml in this the path inside which div the html must be kept is determined by the programmer.
var friendsID = ['id1','id2','id3'];
var i=0;
var statement =[0,0,0];
var friendName = ['name1','name2','name3'];
console.log(friendName[2]);
idplace();
function idplace(){
for(i=0;i<friendsID.length;i++)
{
statement[i]="<a href='google.com/"+friendsID[i]+"'>"+friendName[i]+"</a><br>";
console.log(statement[i]);
document.getElementById("hello").innerHTML+=statement[i];
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div id="hello"></div>
<script src="./java.js"></script>
</body>
</html>
You can do something like this
const friendsID = ["id1", "id2", "id3"]
const friendsName = ["name1", "name2", "name3"]
let i = 0;
for (i = 0; i < friendsID.length; i++) {
let list = '' + friendsName[i] + ""
$(".list-group").append(list)
}
<div class="list-group">
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
check this out
https://jsfiddle.net/cloud_zero/hacLpe3g/4/
var arry1 = ["name1", "name2", "name3"];
var arry2 = ["id1", "id2", "id3"];
// merging two array
var result = arry1.reduce(function(acc, cur, index) {
return Object.assign(acc, { [arry2[index]]: cur })
}, {})
// generating links
var text = Object.keys(result).map(function(key) {
return `${ result[key] }`;
});
// finally adding to dom
document.querySelector('.list-group').innerHTML = text.join('');
first i merged two array to object (result)
then i generate links from the result
lastly linked added to DOM
First of all thank you for your great solutions!
I also tried my best and came up with this here.
var friendsIDs = ["id1", "id2", "id3"];
var friendsNames = ["name1", "name2", "name3"];
var friendLinks = [];
for (i=0; i < friendsIDs.length; i++){
friendLinks.push("<a href=/dashboard/" + friendsIDs[i] + " class=\'list-group item list-group-item-action\' >" + friendsNames[i] + "</a>")
}
//Create HTML Element for the Company Relations
var linkTarget = document.getElementById('linkTarget');
for(i=0; i < friendLinks.length; i++){
linkTarget.innerHTML += friendLinks[i];
}
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet"/>
<div class="list-group" id="linkTarget"></div>
Just noticed today that template literals with html tags don't work, or maybe I wrote it wrong?
I tried to include p tags in the template literals (which I commented out in the snippet), but it didn't work. Does anyone have any ideas? Thanks!
var blueBtn = document.getElementById('btn');
var aniBox = document.getElementById('animal-info');
blueBtn.addEventListener('click', function() {
var ourRequest = new XMLHttpRequest();
ourRequest.open('GET', 'https://learnwebcode.github.io/json-example/animals-1.json');
ourRequest.onload = function() {
var ourData = JSON.parse(ourRequest.responseText);
addHTML(ourData)
};
ourRequest.send();
});
function addHTML(data) {
var content = '';
for (let i of data) {
console.log(i);
content += '<p>' + i.name + ' is a ' + i.species + '.</p>';
//content += '`<p>${i.name} is a ${i.species}.</p>`'; <--this one doesn't work
}
aniBox.insertAdjacentHTML('beforeend', content);
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>JSON and AJAX</title>
</head>
<body>
<header>
<h1>JSON and AJAX</h1>
<button id="btn">Fetch Info for 3 New Animals</button>
</header>
<div id="animal-info"></div>
<script src="js/main.js"></script>
</body>
</html>
Templates are needed to be enclosed in backticks. You don't need to enclose template in quotes again.
You need to change this:
'`<p>${i.name} is a ${i.species}.</p>`'
to this:
`<p>${i.name} is a ${i.species}.</p>`
The former is just a plain JavaScript string, but the latter is the template literal syntax and it allows the sections in ${ ... } to be interpolated.
See the following working example:
var blueBtn = document.getElementById('btn');
var aniBox = document.getElementById('animal-info');
blueBtn.addEventListener('click', function() {
var ourRequest = new XMLHttpRequest();
ourRequest.open('GET', 'https://learnwebcode.github.io/json-example/animals-1.json');
ourRequest.onload = function() {
var ourData = JSON.parse(ourRequest.responseText);
addHTML(ourData)
};
ourRequest.send();
});
function addHTML(data) {
var content = '';
for (let i of data) {
console.log(i);
// content += '<p>' + i.name + ' is a ' + i.species + '.</p>';
content += `<p>${i.name} is a ${i.species}.</p>`;
}
aniBox.insertAdjacentHTML('beforeend', content);
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>JSON and AJAX</title>
</head>
<body>
<header>
<h1>JSON and AJAX</h1>
<button id="btn">Fetch Info for 3 New Animals</button>
</header>
<div id="animal-info"></div>
<script src="js/main.js"></script>
</body>
</html>
Read more about template literals in the documentation.