appendChild odd behavior in javascript - javascript

In the procedure of creating and appending elements to a webpage, I faced an odd behavior of javascript, that is replacing a child with another instead of appending. here is the code:
var window = document.createElement("div"); //the minesweeper game window
window.setAttribute("class", "window");
document.body.appendChild(window);
var title_bar = document.createElement("div");//the title bar of the window
title_bar.setAttribute("class", "title-bar");
window.appendChild(title_bar);
var game_title = document.createElement("span");//the title of the game
game_title.setAttribute("id", "game-title");
game_title.innerHTML = "Minesweeper Online - Beginner!";
title_bar.appendChild(game_title);
var right_corner_div = document.createElement("div");// right corner buttons
title_bar.appendChild(right_corner_div);
var btn_minimize = document.createElement("span");//the minimize button
btn_minimize.setAttribute("class", "btn");
btn_minimize.setAttribute("id", "btn-minimize");
btn_minimize.innerHTML = "-";
right_corner_div.appendChild(btn_minimize);
var btn_close = document.createElement("span");//the close button
btn_close.setAttribute("class", "btn");
btn_close.setAttribute("id", "btn-close");
btn_close.style.marginLeft = "3px";
btn_close.innerHTML = "×";
right_corner_div.appendChild(btn_close);
var top = document.createElement("div");//top of window div, underneath the title bar
title_bar.setAttribute("class", "top");
window.appendChild(top);
but unlike what I expect to see as the result, the latest div with the class attribute of top replaces the first div with the class attribute of title-bar. why does this happen?

You have title_bar here instead of top (second last line in your question):
var top = document.createElement("div");
*title_bar*.setAttribute("class", "top");
window.appendChild(top);
Replace that with top and it should work.
By the way, don't name a variable window in a browser, since that is what the global object reference is assigned to. Call your variable game_window or something else along those lines instead.
Also you probably don't care about the actual HTML class attribute of your elements and should set the className property directly instead:
top.className = "top"; // instead of top.setAttribute("class", "top");

Related

innerHTML is not working inside a function

I'm a beginner in Javascript programming. innerHTML method is not working in a function to update content of a HTML element.
My JS code is :
$(':button').on("click", function() {
// reference clicked button via: $(this)
var buttonElementId = $(this).attr('id');
var sliceId = buttonElementId.charAt(buttonElementId.length - 1);
bringData(sliceId);
})
function bringData(id) {
var a = localStorage.getItem("Blogs")
var b = JSON.parse(a)
console.log(b[id].blogHeader)
document.getElementById("foo").innerHTML = b[id].blogHeader
}
Buttons and element which has id of "foo" are at different HTML pages. I want to update content of that element after clicking any button from other page, but it is not working. The content still remains same. What is my mistake ?
Note : If I use innerHTML property out of a function, it works and content is changing.

Wrapping a DIV around a hyperlink created using appendChild

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>

Error using insertBefore & appendChild while creating element

Trying to append a button to both the top and bottom of the body tag, however it's only performing whichever one of the two is last. Am I missing something obvious here?
var msg_node = document.createElement("a");
msg_node.setAttribute("onclick", "collapseAll()");
msg_node.setAttribute("href", "javascript:void(0)");
msg_node.setAttribute("class", "kc_button");
var msg_textnode = document.createTextNode('COLLAPSE ALL');
msg_node.appendChild(msg_textnode);
document.getElementsByTagName('body')[0].appendChild(msg_node); // supposed to make button
document.body.insertBefore(msg_node, document.body.children[0]); // makes only this button
Clone the node before appending it the second time:
var msg_node = document.createElement("a");
msg_node.setAttribute("onclick", "collapseAll()");
msg_node.setAttribute("href", "javascript:void(0)");
msg_node.setAttribute("class", "kc_button");
var msg_textnode = document.createTextNode('COLLAPSE ALL');
msg_node.appendChild(msg_textnode);
document.getElementsByTagName('body')[0].appendChild(msg_node); // supposed to make button
document.body.insertBefore(msg_node.cloneNode(true), document.body.children[0]); // makes only this button

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

Javascript Custom Alert Box with Image alignment

I Have created Custom Alert Box in Javascript . I Have added text with images. but It is not align proberly. It came some thing like this.
I am trying to add the correct mark and text with same line, how can I achieve this. can anyone please help me. I have added my Custom alert box Function below.
function createCustomAlert(txt, string_url,fd) {
// shortcut reference to the document object
d = document;
// if the modalContainer object already exists in the DOM, bail out.
if (d.getElementById("modalContainer")) return;
// create the modalContainer div as a child of the BODY element
mObj = d.getElementsByTagName("body")[0].appendChild(d.createElement("div"));
mObj.id = "modalContainer";
// make sure its as tall as it needs to be to overlay all the content on the page
mObj.style.height = document.documentElement.scrollHeight + "px";
// create the DIV that will be the alert
alertObj = mObj.appendChild(d.createElement("div"));
alertObj.id = "alertBox";
// MSIE doesnt treat position:fixed correctly, so this compensates for positioning the alert
if (d.all && !window.opera) alertObj.style.top = document.documentElement.scrollTop + "px";
// center the alert box
alertObj.style.left = (d.documentElement.scrollWidth - alertObj.offsetWidth) / 2 + "px";
// create an H1 element as the title bar
h1 = alertObj.appendChild(d.createElement("h1"));
h1.appendChild(d.createTextNode(ALERT_TITLE));
btn2 = alertObj.appendChild(d.createElement("img"));
btn2.id = "fd";
btn2.src = fd;
// create a paragraph element to contain the txt argument
msg = alertObj.appendChild(d.createElement("p"));
msg.innerHTML = txt;
// create an anchor element to use as the confirmation button.
//btn = alertObj.appendChild(d.createElement("a"));
//btn.id = "closeBtn";
//btn.appendChild(d.createTextNode(ALERT_BUTTON_TEXT));
//btn.href = "";
btn = alertObj.appendChild(d.createElement("img"));
btn.id = "closeBtn";
btn.src = 'new-go-next2.png';
btn.href="#ss";
//btn.height="30px";
//btn.width="30px";
//btn.href="#";
// set up the onclick event to remove the alert when the anchor is clicked
btn.onclick = function () { removeCustomAlert(); window.location = string_url; return false; }
}
well yes creating a table would be a great approach to solve your problems , btw u can also try some internal divs with proper position anf the element having correct float attribute
Rather creating div element create table with two Columns. First of which will contain 'Image' for OK and Second one will contain your 'Text'.
Check if this helps.

Categories

Resources