Wrapping a DIV around a hyperlink created using appendChild - javascript

I have a bit of JS to add an email hyperlink to a page, after a DIV with an ID value of section_form_id:
// build email
var elmNewContentCustomer = document.createElement('a');
var elmFoo = document.getElementById('section_form_id');
elmNewContentCustomer.href = 'mailto:me#example.com?subject=Something';
elmNewContentCustomer.setAttribute("style", "color:blue;");
elmNewContentCustomer.setAttribute("id", "email_customer_id");
elmNewContentCustomer.appendChild(document.createTextNode('Email Customer'));
elmFoo.parentNode.insertBefore(elmNewContentCustomer, elmFoo.nextSibling);
This works fine. However, I'd like to put the hyperlink inside a DIV so I set the style attributes of the DIV.
I tried using this method, which was to create a DIV, and insert it before the email block using appendChild but it doesn't work:
var elmNewEmailDev = document.createElement('div');
var elmFoo2 = document.getElementById('email_customer_id');
elmNewEmailDev.setAttribute("style", "background:yellow;");
elmNewEmailDev.appendChild(elmFoo.parentNode.insertBefore(elmNewContentCustomer, elmFoo.nextSibling));
elmFoo2.parentNode.insertBefore(elmNewEmailDev, elmFoo.elmFoo2);
How can I wrap a DIV around the hyperlink so I can then use setAttribute to be able to control the style of that DIV?

Follow this method your get result as you want.
var myEmailLink = "<a href='mailto:a#b.com'>a#b.com</a>";
var myDiv = document.getElementById("section_form_id");
myDiv.insertAdjacentHTML('afterEnd', myEmailLink )
<div id="section_form_id">
My Div Here
</div>

Related

Add element to a div with javascript

I want to add an element (child, div) to a mother-div, that already has one or more children. I made a script for this action but when I execute the script I am not able to manipulate style attributes afterwards. So I assume I did something wrong in my creation-script. I also added a console message (end of the script) and that also indicates there are no style attributes filled in at the new div. So, please could someone indicate what the reason is...
As I am quite new to javascript I assume the reason is quite simple. But although I checked many other questions and solutions, I do not get the proper solution for my issue. I think it should be in appendChild or insertBefore.
function preparevideo(videonaam, titel) {
// add a div to the video-div
const nieuwetitel = document.createElement("div");
// give the new div an id so it will be unique
nieuwetitel.id = videonaam + '-id';
// give the div a class for the markup
nieuwetitel.className = 'page-roel-video-titel';
// create the text in the div
const textnode = document.createTextNode(titel);
// add the textnode to the div
nieuwetitel.appendChild(textnode);
// find the element where the new div should be added to
let videomodule = document.getElementById(videonaam);
// and finally add the new div to the video-div, as the first child
videomodule.insertBefore(nieuwetitel, videomodule.children[0]);
console.log('-------after adding div------');
console.log('-------complete style of titleblock------');
console.log(document.getElementById(videonaam + '-id').style);
console.log('prepare video afgerond');
}
preparevideo("naam1","Eerste video");
<div id="naam1"></div>
As you didn't set any style attribute before console.log that's why you didn't get any result. After implementing some style, you can log the the style. Then you will see the difference.
Here I added some style before the console.log
function preparevideo(videonaam, titel) {
// add a div to the video-div
const nieuwetitel = document.createElement("div");
// give the new div an id so it will be unique
nieuwetitel.id = videonaam + '-id';
// give the div a class for the markup
nieuwetitel.className = 'page-roel-video-titel';
// create the text in the div
const textnode = document.createTextNode(titel);
// add the textnode to the div
nieuwetitel.appendChild(textnode);
// find the element where the new div should be added to
let videomodule = document.getElementById(videonaam);
// and finally add the new div to the video-div, as the first child
videomodule.insertBefore(nieuwetitel, videomodule.children[0]);
// Applying style
document.getElementById(videonaam + '-id').style.backgroundColor = 'red';
document.getElementById(videonaam + '-id').style.color = 'white'
console.log('-------after adding div------');
console.log('-------complete style of titleblock------');
console.log(document.getElementById(videonaam + '-id').style);
console.log('prepare video afgerond');
}
preparevideo("naam1","Eerste video");
<div id="naam1"></div>
You already gave it a class, you can target it in your css and added the needed styles
The problem is that there is no unique id value for nieuwetitel element generated. When you use getElementById() method you get only first element from DOM.

javascript create div and append it next to a child element without id

Using the solution suggested here: https://stackoverflow.com/a/32135318/10279127 i'm trying to create a new div, and append it inside a parent div with id, next to a child <a> html element.
html:
<div id="div0">
anchor text
// I'd like to place the new div here
</div>
js:
Element.prototype.appendAfter = function(element) {
element.parentNode.insertBefore(this, element.nextSibling);
}, false;
var NewElement = document.createElement('div');
NewElement.id = 'newDivID';
var tToAfter = $('#div' + index + ' > a'); // this is what i tried but doesn't work
NewElement.appendAfter(tToAfter);
If inside .appendAfter(...) instead of tToAfter i write document.getElementById('randomElementId') it works and appends it, so i think must be pure javascript, is there a way in js to do something like: document.getElementById('div' + index).firstChild to get the <a> ?
Or to make it entirely with jQuery using the insertAfter (https://stackoverflow.com/a/8707793/10279127) ?
you can select inside div#div0 by using
const anchor = document.querySelector("#div0>a");
You can simplify your approach by using insertAdjacentElement. For example (the css is irrelevant - just there so you can visually see the inserted div):
const anchor = document.querySelector('#div0 a');
const elem = document.createElement('div');
elem.id = 'newDivID';
anchor.insertAdjacentElement('afterend', elem);
div:not(#div0) {
height: 20px;
background-color: green;
}
<div id="div0">
anchor text
// I'd like to place the new div here
</div>

On search/highlight click -> existing div becomes wrapped with existing span

I have a problem with javascript search and highlight text.
For example, there is existing span element and existing div element.
Problem is that if I click on search button for some reason div element becomes a child of span element.
To explain it better I have created JS fiddle to show the problem:
function highlightSearch() {
$('span').removeClass('highlighted');
var text = document.getElementById('query').value;
var query = new RegExp("(\\b" + text + "\\b(?!([^<]+)?>))", "gim");
var e = document.getElementById("searchText").innerHTML;
var enew = e.replace(/(<span class='highlighted'>|<\/span>)/igm, "");
document.getElementById("searchText").innerHTML = enew;
var newe = enew.replace(query, "<span class='highlighted'>$1</span>");
document.getElementById("searchText").innerHTML = newe;
}
Check problem on : JSfiddle
Well, you are removing all </span> tags from the innerHTML in this line:
var enew = e.replace(/(<span class='highlighted'>|<\/span>)/igm, "");
And therefore also the </span> of .glyphicon. This is why the element becomes wrapped.
Btw: An exception is thrown: ReferenceError: highlightSearch is not defined

Not able to append an img tag to a p tag

I'm a complete beginner in JavaScript and I am trying to create a script which is fired when a "file input" element of the page gets a file loaded. The script should basically create a p element, insert in it an img, a innerText and a span, hence append all this into a form. Everything works fine with the script below, except for the img:
function visualUploadFile() {
var obj = document.getElementById("hidden_file").files[0].name;
//create p object to append to the form
var pobj = document.createElement("p");
pobj.className = "form_line_file";
//nest icon inside the object
var imgico = document.createElement("img");
imgico.src = "load-ico.png";
//append img to the p - THE OBJECT IS NOT APPENDED
pobj.appendChild(imgico);
//nest file name as inner Text to the p
pobj.innerText = obj;
//create span object to write "rimuovi"
var spanobj = document.createElement("span");
spanobj.className = "rimuovi_file";
spanobj.innerHTML = "rimuovi";
//append span to the p
pobj.appendChild(spanobj);
//get form and append p child
var bigForm = document.getElementById("offerta_form");
bigForm.appendChild(pobj);
}
Here is the HTML after the script has been executed, as you can see only the img is missing:
<p class="form_line_file"> <!--p object correctly appended to the form-->
Immagine.png <!--inner Text properly appended-->
<span class="rimuovi_file"> <!--span object correctly appended-->
rimuovi
</span>
</p>
Probably is a stupid mistake, but I'm not being able to sort it out. Could anyone please tell me what I'm doing wrong not to be able to get the img appended as for the span?
The way you are adding file name label is incorrect. Setting innerText overwrites image. Instead of
pobj.innerText = obj;
try this:
pobj.appendChild(document.createTextNode(obj));

How to append content to querySelectorAll element with innerHTML/innerText?

I currently have my class element:
var frame_2 = document.querySelectorAll(".name");
Currently this div is empty. I now want to "append/add" some content to that div - I had a go with innerHTML + innerText but for some reason nothing seems to be added.
Example:
frame_2.innerHTML = '<img src="image.gif" />';
and
frame_2.innerText = 'some text';
Any suggestions? Im not sure if there are ways of doing the same - or performance'wise something better?
this gives you a list of elements that contain the class name
var name=document.querySelectorAll(".name");
you want the first element?
name[0].textContent='some text';
This gives you one single element, the first one.
var name=document.querySelector(".name");
name.textContent='some text';
To append stuff
name.appendChild(document.createTextNode('pizza'));
name.appendChild(document.createElement('div')).textContent='spaghetti';
name.appendChild(document.createElement('img')).src='cookie.jpg';
EDIT
To get the elements by classname, then retrieve the id :
var names=document.querySelectorAll(".name"),l;
while(l--){
console.log(names[l].id);
}
or if i didn't understand correctly
html
<div class="spaghetti" id="pizza"></div>
js
document.querySelector(".spaghetti#pizza")
EDIT2
html
<div id="container1"><div class="my-class"></div></div>
js
document.querySelector("#container1>.my-class")
Easier solution, any use case. Query your selector:
let find = document.querySelector('.selector');
create some html as a string
let html = `put your html here`;
create element from string
let div = document.createElement('div');
div.innerHTML = html;
Append new html you created to selector
find.appendChild(div);

Categories

Resources