Wrap a created text node with an element WITHOUT jQuery - javascript

I'm editing a script that at one point does the following:
err_node = document.createTextNode(err_decoded_str);
However I need the resulting text node to be wrapped in <label class="error">generated error node in here</label>
How can this be done without using jQuery? If needs be I can change createTextNode() to a different function to achieve this.

So change it to use createElement instead
err_node = document.createTextNode(err_decoded_str);
to
err_node = document.createElement("label");
err_node.className = "error";
err_node.innerHTML = err_decoded_str;
If you want, you can create a textnode and append it to the err_node.
err_node = document.createElement("label");
err_node.className = "error";
var err_textnode = document.createTextNode(err_decoded_str);
err_node.appendChild(err_textnode);

When you wrap the text in a <label> it becomes an element instead of a text node. Look at document.createElement in the MDN documentation here.

label = document.createElement('label');
label.className = 'error';
label.appendChild(document.createTextNode(err_decoded_str));
// attach the label to where ever its supposed to go

err_node = document.createTextNode(err_decoded_str);
var label = document.createElement("label"); // create label element
label.classList.add("error"); // add error class to label
label.appendChild(err_node); // append err_node to label
console.log(label);

Related

How do we convert jQuery prepend() to VanillaJS [duplicate]

How can I implement prepend and append with regular JavaScript without using jQuery?
Here's a snippet to get you going:
theParent = document.getElementById("theParent");
theKid = document.createElement("div");
theKid.innerHTML = 'Are we there yet?';
// append theKid to the end of theParent
theParent.appendChild(theKid);
// prepend theKid to the beginning of theParent
theParent.insertBefore(theKid, theParent.firstChild);
theParent.firstChild will give us a reference to the first element within theParent and put theKid before it.
Perhaps you're asking about the DOM methods appendChild and insertBefore.
parentNode.insertBefore(newChild, refChild)
Inserts the node newChild as a child of parentNode before the
existing child node refChild. (Returns newChild.)
If refChild is null, newChild is added at the end of the list of
children. Equivalently, and more readably, use
parentNode.appendChild(newChild).
You didn't give us much to go on here, but I think you're just asking how to add content to the beginning or end of an element?
If so here's how you can do it pretty easily:
//get the target div you want to append/prepend to
var someDiv = document.getElementById("targetDiv");
//append text
someDiv.innerHTML += "Add this text to the end";
//prepend text
someDiv.innerHTML = "Add this text to the beginning" + someDiv.innerHTML;
Pretty easy.
If you want to insert a raw HTML string no matter how complex, you can use:
insertAdjacentHTML, with appropriate first argument:
'beforebegin'
Before the element itself.
'afterbegin'
Just inside the element, before its first child.
'beforeend'
Just inside the element, after its last child.
'afterend'
After the element itself.
Hint: you can always call Element.outerHTML to get the HTML string representing the element to be inserted.
An example of usage:
document.getElementById("foo").insertAdjacentHTML("beforeBegin",
"<div><h1>I</h1><h2>was</h2><h3>inserted</h3></div>");
DEMO
Caution: insertAdjacentHTML does not preserve listeners that where attached with .addEventLisntener.
I added this on my project and it seems to work:
HTMLElement.prototype.prependHtml = function (element) {
const div = document.createElement('div');
div.innerHTML = element;
this.insertBefore(div, this.firstChild);
};
HTMLElement.prototype.appendHtml = function (element) {
const div = document.createElement('div');
div.innerHTML = element;
while (div.children.length > 0) {
this.appendChild(div.children[0]);
}
};
Example:
document.body.prependHtml(`Hello World`);
document.body.appendHtml(`Hello World`);
Here's an example of using prepend to add a paragraph to the document.
var element = document.createElement("p");
var text = document.createTextNode("Example text");
element.appendChild(text);
document.body.prepend(element);
result:
<p>Example text</p>
In order to simplify your life you can extend the HTMLElement object. It might not work for older browsers, but definitely makes your life easier:
HTMLElement = typeof(HTMLElement) != 'undefined' ? HTMLElement : Element;
HTMLElement.prototype.prepend = function(element) {
if (this.firstChild) {
return this.insertBefore(element, this.firstChild);
} else {
return this.appendChild(element);
}
};
So next time you can do this:
document.getElementById('container').prepend(document.getElementById('block'));
// or
var element = document.getElementById('anotherElement');
document.body.prepend(div);
In 2017 I know for Edge 15 and IE 12, the prepend method isn't included as a property for Div elements, but if anyone needs a quick reference to polyfill a function I made this:
HTMLDivElement.prototype.prepend = (node, ele)=>{
try { node.insertBefore(ele ,node.children[0]);}
catch (e){ throw new Error(e.toString()) } }
Simple arrow function that's compatible with most modern browsers.
var insertedElement = parentElement.insertBefore(newElement, referenceElement);
If referenceElement is null, or undefined, newElement is inserted at the end of the list of child nodes.
insertedElement The node being inserted, that is newElement
parentElement The parent of the newly inserted node.
newElement The node to insert.
referenceElement The node before which newElement is inserted.
Examples can be found here: Node.insertBefore
You can also use unshift() to prepend to a list
document.write() is not a good practice, some browsers like Chrome give you a warning if you use it, and it may be a bad solution if you are providing it to a customer, they don't want to use your code and see warnings in the debug console!
Also jQuery may also be a bad thing if you are giving your code to a customer who already uses jQuery for other functionality on their site, there will be a conflict if there is already a different version of jQuery running.
If you want to insert content into an iframe, and do that with pure JS, and with no JQuery, and without document.write(), I have a solution.
You can use the following steps
1.Select your iframe:
var iframe = document.getElementById("adblock_iframe");
2.Create an element that you want to insert into the frame, let's say an image:
var img = document.createElement('img');
img.src = "https://server-name.com/upload/adblock" + id + ".jpg";
img.style.paddingLeft = "450px";
//scale down the image is we have a high resolution screen on the client side
if (retina_test_media == true && high_res_test == true) {
img.style.width = "200px";
img.style.height = "50px";
} else {
img.style.width = "400px";
img.style.height = "100px";
}
img.id = "image";
3.Insert the image element into the iframe:
iframe.contentWindow.document.body.appendChild(img);
This is not best way to do it but if anyone wants to insert an element before everything, here is a way.
var newElement = document.createElement("div");
var element = document.getElementById("targetelement");
element.innerHTML = '<div style="display:none !important;"></div>' + element.innerHTML;
var referanceElement = element.children[0];
element.insertBefore(newElement,referanceElement);
element.removeChild(referanceElement);

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

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);

How can I implement prepend and append with regular JavaScript?

How can I implement prepend and append with regular JavaScript without using jQuery?
Here's a snippet to get you going:
theParent = document.getElementById("theParent");
theKid = document.createElement("div");
theKid.innerHTML = 'Are we there yet?';
// append theKid to the end of theParent
theParent.appendChild(theKid);
// prepend theKid to the beginning of theParent
theParent.insertBefore(theKid, theParent.firstChild);
theParent.firstChild will give us a reference to the first element within theParent and put theKid before it.
Perhaps you're asking about the DOM methods appendChild and insertBefore.
parentNode.insertBefore(newChild, refChild)
Inserts the node newChild as a child of parentNode before the
existing child node refChild. (Returns newChild.)
If refChild is null, newChild is added at the end of the list of
children. Equivalently, and more readably, use
parentNode.appendChild(newChild).
You didn't give us much to go on here, but I think you're just asking how to add content to the beginning or end of an element?
If so here's how you can do it pretty easily:
//get the target div you want to append/prepend to
var someDiv = document.getElementById("targetDiv");
//append text
someDiv.innerHTML += "Add this text to the end";
//prepend text
someDiv.innerHTML = "Add this text to the beginning" + someDiv.innerHTML;
Pretty easy.
If you want to insert a raw HTML string no matter how complex, you can use:
insertAdjacentHTML, with appropriate first argument:
'beforebegin'
Before the element itself.
'afterbegin'
Just inside the element, before its first child.
'beforeend'
Just inside the element, after its last child.
'afterend'
After the element itself.
Hint: you can always call Element.outerHTML to get the HTML string representing the element to be inserted.
An example of usage:
document.getElementById("foo").insertAdjacentHTML("beforeBegin",
"<div><h1>I</h1><h2>was</h2><h3>inserted</h3></div>");
DEMO
Caution: insertAdjacentHTML does not preserve listeners that where attached with .addEventLisntener.
I added this on my project and it seems to work:
HTMLElement.prototype.prependHtml = function (element) {
const div = document.createElement('div');
div.innerHTML = element;
this.insertBefore(div, this.firstChild);
};
HTMLElement.prototype.appendHtml = function (element) {
const div = document.createElement('div');
div.innerHTML = element;
while (div.children.length > 0) {
this.appendChild(div.children[0]);
}
};
Example:
document.body.prependHtml(`Hello World`);
document.body.appendHtml(`Hello World`);
Here's an example of using prepend to add a paragraph to the document.
var element = document.createElement("p");
var text = document.createTextNode("Example text");
element.appendChild(text);
document.body.prepend(element);
result:
<p>Example text</p>
In order to simplify your life you can extend the HTMLElement object. It might not work for older browsers, but definitely makes your life easier:
HTMLElement = typeof(HTMLElement) != 'undefined' ? HTMLElement : Element;
HTMLElement.prototype.prepend = function(element) {
if (this.firstChild) {
return this.insertBefore(element, this.firstChild);
} else {
return this.appendChild(element);
}
};
So next time you can do this:
document.getElementById('container').prepend(document.getElementById('block'));
// or
var element = document.getElementById('anotherElement');
document.body.prepend(div);
In 2017 I know for Edge 15 and IE 12, the prepend method isn't included as a property for Div elements, but if anyone needs a quick reference to polyfill a function I made this:
HTMLDivElement.prototype.prepend = (node, ele)=>{
try { node.insertBefore(ele ,node.children[0]);}
catch (e){ throw new Error(e.toString()) } }
Simple arrow function that's compatible with most modern browsers.
var insertedElement = parentElement.insertBefore(newElement, referenceElement);
If referenceElement is null, or undefined, newElement is inserted at the end of the list of child nodes.
insertedElement The node being inserted, that is newElement
parentElement The parent of the newly inserted node.
newElement The node to insert.
referenceElement The node before which newElement is inserted.
Examples can be found here: Node.insertBefore
You can also use unshift() to prepend to a list
document.write() is not a good practice, some browsers like Chrome give you a warning if you use it, and it may be a bad solution if you are providing it to a customer, they don't want to use your code and see warnings in the debug console!
Also jQuery may also be a bad thing if you are giving your code to a customer who already uses jQuery for other functionality on their site, there will be a conflict if there is already a different version of jQuery running.
If you want to insert content into an iframe, and do that with pure JS, and with no JQuery, and without document.write(), I have a solution.
You can use the following steps
1.Select your iframe:
var iframe = document.getElementById("adblock_iframe");
2.Create an element that you want to insert into the frame, let's say an image:
var img = document.createElement('img');
img.src = "https://server-name.com/upload/adblock" + id + ".jpg";
img.style.paddingLeft = "450px";
//scale down the image is we have a high resolution screen on the client side
if (retina_test_media == true && high_res_test == true) {
img.style.width = "200px";
img.style.height = "50px";
} else {
img.style.width = "400px";
img.style.height = "100px";
}
img.id = "image";
3.Insert the image element into the iframe:
iframe.contentWindow.document.body.appendChild(img);
This is not best way to do it but if anyone wants to insert an element before everything, here is a way.
var newElement = document.createElement("div");
var element = document.getElementById("targetelement");
element.innerHTML = '<div style="display:none !important;"></div>' + element.innerHTML;
var referanceElement = element.children[0];
element.insertBefore(newElement,referanceElement);
element.removeChild(referanceElement);

Get innerHTML value from dynamically generated textbox (in javascript)

I'm using JavaScript to dynamically generate a dialogue box (it's a div element), containing a textbox and a submit button. I plan on submitting the value in the textbox to another page using AJAX.
My problem is that I can generate my textbox just fine, but I can't get the value from it. innerHTML comes back blank every time. I'm not sure what I'm doing wrong.
// Generate dialogue box using div
function create_div_dynamic()
{
//Create the div element
dv = document.createElement('div');
//unique tags
var unique_div_id = 'mydiv' + Math.random() * .3245;
var unique_textbox_id = 'mytext' + Math.random() * .3245;
//Set div id
dv.setAttribute('id',unique_div_id);
//Set div style
dv.style.position = 'absolute';
dv.style.left = '100 px';
dv.style.top = '100 px';
dv.style.width = '500px';
dv.style.height = '100px';
dv.style.padding = '7px';
dv.style.backgroundColor = '#fdfdf1';
dv.style.border = '1px solid #CCCCCC';
dv.style.fontFamily = 'Trebuchet MS';
dv.style.fontSize = '13px';
//Create textbox element
txt = document.createElement('input');
txt.setAttribute('id',unique_textbox_id);
txt.setAttribute('type','text');
txt.style.marginRight = '10px';
//Add textbox element to div
dv.appendChild(txt)
//Add the div to the document
document.body.appendChild(dv);
dv.innerHTML += '<input type="button" id="mysubmit" value="Read Textbox" onclick="javascript:alert(\'' + document.getElementById(unique_textbox_id).innerHTML + '\');" />';
}
Textarea elements don't have an innerHTML property. Just read the value property like you would with any other form element.
document.getElementById(unique_textbox_id).value
The input type="text" fields have no innerHTML, they are usually represented as self-closing tags.
Use the value attribute instead:
document.getElementById(unique_textbox_id).value
I have to create the div element, add it to the document, and THEN add the children (textbox and submit button).
No, you don't in general have to do that. What was causing your problem was this:
...'onclick="javascript:alert(\'' + document.getElementById(unique_textbox_id).innerHTML + '\');" />';
That access to document.getElementById().innerHTML is occurring at the time you create the string, that is during the execution of create_div_dynamic(), not when the button is pressed. At that point, the field has just been created and has no .value. (It also has no .innerHTML, but then it never will as it's an input element.)
Your revised code uses a proper JavaScript function which is called at onclick time, and fixes the property to value, so that's OK. This approach also doesn't die when there are apostrophes or backslashes in the value string.
dv.innerHTML += '<input ...
This serialises all the content in ‘dv’ to HTML text, then adds the string, and parses all the HTML back into DOM objects. This is really inefficient, and in the process you lose all JavaScript properties on the object, including event handlers and listeners.
“innerHTML+=” is always a mistake. Never use it.
txt.setAttribute('id',unique_textbox_id);
Don't use setAttribute(), it doesn't work for certain attributes under IE. Instead use the more readable DOM-HTML properties:
txt.type= 'text';
txt.id= unique_textbox_id;
For others in my boat, I want to show the solution. It turns out that I was adding elements in the wrong order.
I have to create the div element, add it to the document, and THEN add the children (textbox and submit button).
//DIV
dv = document.createElement('div');
dv.setAttribute('id',unique_div_id);
dv.style.position = 'absolute';
dv.style.left = xx + 'px';
dv.style.top = yy + 'px';
dv.style.width = '500px';
dv.style.height = '20px';
dv.style.padding = '7px';
dv.style.backgroundColor = '#fdfdf1';
dv.style.border = '1px solid #CCCCCC';
dv.style.fontFamily = 'Trebuchet MS';
dv.style.fontSize = '13px';
//Add div element to body
document.body.appendChild(dv);
//TEXTBOX
txt = document.createElement('input');
txt.setAttribute('id',unique_textbox_id);
txt.setAttribute('type','text');
txt.style.marginRight = '10px';
//Add textbox to div element
document.getElementById('mydiv').appendChild(txt);
var sbt = document.createElement('input');
sbt.setAttribute('id','mysubmit');
sbt.setAttribute('type','submit');
sbt.setAttribute('value','GO');
sbt.onclick = function() { alert(document.getElementById('mytext').value); };
//Add submit to div element
document.getElementById('mydiv').appendChild(sbt);
Once this is done, and I use the .value, all goes well.
$cid =$_REQUEST['cid'];
$name =addslashes($_REQUEST['name']);
$email =$_REQUEST['email'];
$comments =$_REQUEST['comments'];
$comment_type=$_REQUEST['type'];
$gstatus =(isset($_REQUEST['gstatus'])) ? $_REQUEST['gstatus'] : 'no';
$user_type =(!empty($_SESSION['user_id'])) ? 'author' : 'user';

Categories

Resources