Appendchild to a specific id - javascript

I'm new to HTML and CSS and I hope to get some help here :D.
I want to create an <a> element at a certain div container with the id navigationPaths, which would be this div container.
<div id="navigationPaths">
This is the part of my javascript code which I want to append to this ID. This is what i already found.
var a = document.createElement('a');
var linkText = document.createTextNode("Path");
a.appendChild(linkText);
a.title = "Path";
a.href = "http://google.com";
document.body.appendChild(a);
The functions I found doesn't really suit my problem so I hope that someone here knows how this works.

As a postscript to Phil's comment, if you didn't want to faff around creating DOM elements, you could create some fully-formed HTML by inserting an HTML string into the element.
const anchor = '<a title="path" href="http://google.com">Path</a>';
const el = document.querySelector('#navigationPaths');
el.insertAdjacentHTML('beforeend', anchor);
<div id="navigationPaths">New anchor: </div>

You can just replace document.body.appendChild(a) with document.getElementById('navigationPaths').appendChild(a)

to get a specified element in javascript you can use document.getElementById('navigationPaths') or document.queryselector('#navigationPaths')
then you can save it in a variable then you can append it as a child to it like this
var a = document.createElement('a');
var linkText = document.createTextNode("Path");
a.appendChild(linkText);
a.title = "Path";
a.href = "http://google.com";
const navigation = document.getElementById('navigation');
navigation.appendChild(a);
<div id="navigation"></div>

Related

how to add a (click) function inside the .ts

I am working on a solution to rewrite links in an HTML element.
I get HTML information via a JSON string 'spanClass1'. In this string I need to rewrite a class to a link. This works wonderfully. Unfortunately, I use hash routing in Angular and can only link further via the toDocument() function. It doesn't work via a normal link name tag
Via span.className.replace(/\D/g, '') I get the ID I need to link to the page.
Unfortunately I was not able to define an Angular (click) function including the ID to the page.
Also, I can't manipulate the code in the .html, only in the .ts.
document.ts
var div = document.createElement('div');
div.innerHTML = spanClass1;
div.querySelectorAll('[class^=doc-]').forEach(function (span) {
var anchor = document.createElement('a');
anchor.href = '/suche#/document/' + span.className.replace(/\D/g, '');
anchor.href = span.className.split('doc-')[1];
anchor.innerHTML = span.innerHTML;
span.parentNode.replaceChild(anchor, span);
});
spanClass1 = div.innerHTML;
toDocument(id) {
window.open('/suche#/document/' + id);
}
JSON
"spanClass1": "blablablablabla <span class=\"doc-158 \">Radleuchter,</span> blablablabla"
How do I add a (click)="toDocument(123)" function to the <a> tag inside the Component.
It seems that you want to add a event listener to a div you are creating at run time. A possible approach is to use the Renderer2 API, as provided by the Angular Team.
In this case, your code would look like the following:
In the constructor:
construct(private _renderer2: Renderer2, ...) { ... };
In the method where you create the div:
var div = document.createElement('div');
this._renderer2.listen(div, 'click', (event) => {
// Code to be run here or callback.
}
div.innerHTML = spanClass1;
...
Furthermore, I would advise some caution on changing the DOM directly. It's best to use the renderer for this since it comes with built it methods that are far safer and expose less risks.
You want to add an event listener to each a and listen for the click event. There are a few pieces of your code that I don't fully understand, but it's basically this:
function toDocument(id) {
window.open('/suche#/document/' + id);
}
var div = document.createElement('div');
div.innerHTML = spanClass1; // what is this?
div.querySelectorAll('[class^=doc-]').forEach(function (span) {
var anchor = document.createElement('a');
var id = span.className.split('doc-')[1];
anchor.href = '/suche#/document/' + span.className.replace(/\D/g, '');
anchor.innerHTML = span.innerHTML;
anchor.addEventListener('click', function() {
toDocument(id);
})
span.parentNode.replaceChild(anchor, span);
});
spanClass1 = div.innerHTML;

Generate html using Javascript

I have a gallery page that is updated often with new images. I use simple HTML to post the photos. My process currently is copy and paste the set of tags for a photo and change the number to correspond with the image file name. E.G. I change the number 047 to 048. Copy-Paste, change it to 049. This goes on until I have reached the number of additional photos. As you can see, this is very inefficient and there must be a better way of doing this. I was wondering if there is a simpler way to achieve this with Javascript? Perhaps generate additional tags by inputing a certain number or range?
Any ideas that would make this process efficient are welcomed please! Thank you!
<div class="cbp-item trim">
<a href="../assets/images/trim/img-trim-047.jpg" class="cbp-caption cbp-lightbox" data-title="">
<div class="cbp-caption-defaultWrap">
<img src="../assets/images/trim/img-trim-047.jpg" alt="">
</div>
</a>
</div>
You could use a templating solution. There are several libraries for that, but you can also implement it yourself.
Here is one way to do that:
Put the HTML for one image in a script tag that has a non-standard language property so the browser will just ignore it
Put some keywords in there that you'll want to replace, e.g. {url}. You can invent your own syntax.
Read that template into a variable
In the JS code, put all the images' URLs in an array of strings
For each element in that array, replace the keywords in the template string with that particular URL, and concatenate all these resulting HTML snippets.
Inject the resulting HTML into the appropriate place in the document.
Here is a snippet doing that:
// Add new images here:
var images = [
"https://upload.wikimedia.org/wikipedia/commons/thumb/e/e0/SNice.svg/330px-SNice.svg.png",
"https://nettemarie357.files.wordpress.com/2014/09/smiley-face.jpg?w=74&h=74",
];
// Load the template HTML
var template = document.querySelector('script[language="text/template"]').innerHTML;
// Use template to insert all the images:
container.innerHTML = images.map(url => template.replace(/{url}/g, url)).join('');
img { max-width: 50px }
<div id="container"></div>
<script language="text/template">
<div class="cbp-item trim">
<a href="{url}" class="cbp-caption cbp-lightbox" data-title="">
<div class="cbp-caption-defaultWrap">
<img src="{url}" alt="">
</div>
</a>
</div>
</script>
This would help you creating it programatically:
var new_row = document.createElement('div');
new_row.className = "cbp-item trim";
var a = document.createElement('a');
a.href = "../assets/images/trim/img-trim-047.jpg";
a.className= "cbp-caption cbp-lightbox";
document.body.appendChild(a);
var div = document.createElement('div');
div.className = "cbp-caption-defaultWrap";
var img = document.createElement('img');
img.src= "../assets/images/trim/img-trim-047.jpg";
div.appendChild(img);
a.appendChild(div);
new_row.appendChild(a);
If it is just about printing HTML, I suggest you to use plugins like Emmet for Sublime Text editor.
When you install this plugin and see how it works, you can simple create a complex html in a way that 'for' loop would do this. This will help you to change only the image/link number of every item.
Check the demo in the link, that I added.
Here's an example in Java Script that will generate the html you will need. Set the total to whatever number you need to generate the number of images you want.
var total = 47;
var hook = document.getElementById('hook');
// Main Node for SlideShow
var node = document.createElement('div');
node.classList = "cbp-item trim";
// Work out the correct number
var n = function(int) {
var length = int.toString().length;
return length === 1
? '00' + int
: length === 2
? '0' + int
: length
}
// Create the item
var createItem = function(int){
// Create Anchor
var a = document.createElement('a');
a.href = '../assets/images/trim/img-trim-' + ( n(int) ) + '.jpg" class="cbp-caption cbp-lightbox';
a.classList = 'cbp-caption cbp-lightbox';
// Create Div
var div = document.createElement('div');
div.classList = 'cbp-caption-defaultWrap';
// Create Image
var img = document.createElement('img');
img.src = '../assets/images/trim/img-trim-' + ( n(int) ) + '.jpg';
img.alt = 'gallery image';
// Finalise Dom Node
var container = div.appendChild(img)
a.appendChild(div);
// Return Final Item
return a
}
// Create Items
for (var i = 1; i < total + 1; i++) {
node.appendChild(createItem(i));
}
// Append Main Node to Hook
hook.appendChild(node);
<div id="hook"></div>

Can't create an anchor for a div tag using createElement?

For the last 20 minutes I've been befuddled by such a simple problem that it's almost embarrassing to ask. Basically I want to create an anchor tag for a div which already exists but I want to use the DOM to create the anchor. For some reason I cannot get this simple problem to work. Tried single quotes and double quotes, moving the script tag from head to body, etc...
Here's the code
<html>
<head>
</head>
<body>
<div id = "image_div">
<img src = "my_image.png" />
</div>
<script type="text/javascript">
var DIV = document.getElementById("image_div");
var anchor = document.createElement("a");
anchor.href = "http://www.stackoverflow.com";
DIV.appendChild(anchor);
</script>
</body>
</html>
Your Example is Working Fine.. And also Append your a Child to DOM, but You have to Insert a text and some Sign for that it is Shown to click..
var DIV = document.getElementById("image_div");
var anchor = document.createElement("a");
anchor.href = "http://www.stackoverflow.com";
anchor.innerText = "Click Me";
DIV.appendChild(anchor);
See Fiddle
Or If you wanna Wrap,the a Anchor tag to img then use :
var DIV = document.getElementById("image_div");
var img1 = document.getElementById("img1");
var anchor = document.createElement("a");
anchor.href = "http://www.stackoverflow.com";
anchor.appendChild(img1);
DIV.appendChild(anchor);
WORKING DEMO
You didn't put any text in the anchor so it won't have any size and thus you won't see it even though it's there.
var DIV = document.getElementById("image_div");
var anchor = document.createElement("a");
anchor.href = "http://www.stackoverflow.com";
anchor.innerHTML = "Click Me"; // <==== Add this line
DIV.appendChild(anchor);

Jquerymobile create button using javascript

i am trying to create href using javascript which should have data-role="button". But the button is not showing. Here is my code.
var a = document.createElement("A");
a.appendChild(document.createTextNode("Skúsiť Znova"));
a.setAttribute("onClick","checkConnection();");
a.setAttribute("data-role","button");
a.setAttribute("data-inline","true");
a.setAttribute("data-corner","false");
I append this to div as child and I can see text and also onClick parameter is working great. But for some reason it isnt showing as button but as normaln href. Any suggestions on how to create jquerymobile button dynamicaly with JS? This is whole code:
$(document).ready(function(){
var a = document.createElement("A");
var div = document.createElement("div");
var span = document.createElement("span");
var p2 = document.createElement("p");
var p = document.createElement("p");
a.appendChild(document.createTextNode("Skúsiť Znova"));
a.setAttribute("onClick","checkConnection();");
a.setAttribute("data-role","button");
a.setAttribute("data-inline","true");
a.setAttribute("data-corner","false");
div.setAttribute("id","alertMessage");
span.appendChild(document.createTextNode("Pripojenie zlyhalo"));
p2.setAttribute("style","text-align: center;");
span.setAttribute("class","red");
p.appendChild(span);
p.appendChild(document.createTextNode(" (skontrolujte nastavenia siete)."));
div.appendChild(p);
p2.appendChild(a);
div.appendChild(p2);
var mainDiv = document.getElementById("alert");
mainDiv.appendChild(div);
$('mainDiv').trigger('create');
var toppos=($(window).height()/2) - ($("#alertMessage").height()/2);
var leftpos=($(window).width()/2) - ($("#alertMessage").width()/2);
$("#alertMessage").css("top", toppos).css("left",leftpos);
});
You can use trigger('create') to apply all of the jQuery Mobile formatting. Full working code:
HTML:
<div id="container"></div>
JavaScript:
var a = document.createElement("A");
a.appendChild(document.createTextNode("Skúsiť Znova"));
a.setAttribute("onClick","checkConnection();");
a.setAttribute("data-role","button");
a.setAttribute("data-inline","true");
a.setAttribute("data-corner","false");
$('#container').append(a).trigger('create');
This can be seen in action here: http://jsfiddle.net/sQ2dA/.
In response to your edits: the issue is that you have mainDiv in quotes, so you are passing a string on this line:
$('mainDiv').trigger('create');
But you should be passing the variable mainDiv:
$(mainDiv).trigger('create');
Please see the working example here: http://jsfiddle.net/P62Cp/.
var a = document.createElement("button");
a.innerText = "Submit";
a.id = "addition";
document.body.appendChild(a);

Basic InnerHTML issue

this is the piece of code that I am using in a loop to append an HTML element to a Google Chrome Extension's popup(.html):
'wordlist' is an array of words.
'rand' is the Random number generating function.
Code:
for (l=1; l<11; l++) {
var i = rand(wordlist.length;
var h1 = document.createElement("h1");
h1.innerHTML = wordlist[i];
document.body.appendChild(h1);
}
There are no pre-existing HTML elements. So, this code is appending 10 random words to a blank page.
Now, instead of the words being appended to the page, I want to append links to the page (eg: http://dictionary.reference.com/browse/**wordlist[i]**, which is basically a dictionary.com query for that particular word). Also, I want this link to be opened in a new Chrome tab when clicked. How do I do this?
P.S: I started learning HTML and JS a day before, and I was too excited to start writing some code. I apologize if I have overlooked a simple Google solution to my problem. Thank you for your time.
for (l=1; l<11; l++) {
var i = rand(wordlist.length);
var a = document.createElement("a");
a.setAttribute('href', 'http://dictionary.reference.com/browse/'.wordlist[i]);
a.setAttribute('target', '_blank');
h1.innerHTML = wordlist[i];
document.body.appendChild(a);
}
Basicly just change h1 to a.
Also set the attribute href (the link) and target (where it should be openend).
If you want to work with the DOM,
for (l=1; l<11; l++) {
var i = rand(wordlist.length;
var a = document.createElement("a");
a.href = "http://dictionary.reference.com/browse/" + wordlist[i];
a.appendChild(document.createTextElement(wordlist[i]));
document.body.appendChild(h1);
}
The following will be faster, since you'll append the HTML only once (and DOM operations are costly):
var html = "";
for (l=1; l<11; l++) {
var i = rand(wordlist.length);
html += "<a href='http://dictionary.reference.com/browse/" + wordlist[i] + "'>"
+ wordlist[i]
+ "</a>";
}
document.body.innerHTML += html;
Try changing your code to the following:
for (l=1; l<11; l++) {
var i = rand(wordlist.length);
var a = document.createElement("a");
a.innerHTML = wordlist[i];
a.href = "http://dictionary.reference.com/browse/" + wordlist[i];
document.body.appendChild(a);
}
I fixed a problem in line 2, you'd omitted a closing parenthesis.
I also more obviously changed your h1 to an a, and added a line that sets its href.
Well its as easy as changing
h1.innerHTML = wordlist[i];
to exatly what you are after, namely:
h1.innerHTML = "<a href='http://dictionary.reference.com/browse/"+wordlist[i]+"' target='_blank'>"+wordlist[i]+"</a>";
To make it open in a new tab you have to add the attribute "target" and give it a value of blank. I think its deprecated in HTML 5 though...

Categories

Resources