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

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

Related

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>

JS: Avoiding modifications of ".innerHTML"

I have some <div> in which I all the time add new objects.
These objects are assigned with listeners.
The problem is that when I add these new objects using .innerHTML, the previous listeners get lost.
Is it possible to create a JS string which represents an HTML object, and to append it as a child without .innerHTML += ... ?
I'll give an example:
var line_num = 0;
function addTextLine(line) {
var lineId = "line_" + line_num;
var lineHtml = "<p id = '" + lineId + "'>" + line + "</p>";
document.getElementById("some_div_id").innerHTML += lineHtml;
document.getElementById(line_id).addEventListener("click", function() {
alert("hello");
});
line_num += 1;
}
The modification of innerHTML of some_dive_id, removes the event listeners of the old <p> objects.
So - is it possible to convert the <p> HTML string into an object, and thus to append it to the some_div_id without modifying its .innerHTML ?
Your problem is that innerHtml erases then recreates the current DOM node; that's why you lose you event listeners.
you can insert your html with insertAdjacentHtml
document.getElementById("some_div_id").insertAdjacentHTML('afterbegin', lineHtml );
the afterbegin parameter assure the inserted html will be a child of your current node.
Look for more infos here: Element.insertAdjacentHTML()
Create the element and append it
var p = document.createElement("p");
p.innerHTML = line;
p.id = line_id; // or p.setAttribute("id", line_id);
p.addEventListener("click", function(){ });
document.getElementById("foo").appendChild(p);
Another option can be to create an element, and set the innerHTML and read the element from there. (First option is better)
var div = document.createElement("div");
div.innerHTML = lineHtml;
//now you can either select the children and append it or append the div.
use element.appendChild().
Your code is not working because everytime you use innerHtml += 'Something' you are removing anything inside that particular element and inserting old content with added string.
Instead you can create element with function and append it to parent element.
Rewriting your code should be:
var line_num = 0;
function addTextLine(line) {
var line = document.createElement('p');
line.id = "line_" + line_num;
line.textContent = line;
line.addEventListener("click", function() {
alert("hello");
});
document.getElementById("some_div_id").appendChild(line);
line_num += 1;
}

Dynamically add new element and change its content

I want to "copy" a certain elements and the change some of the text inside them with a regex.
So far so good: (/w working fiddle - http://jsfiddle.net/8ohzayyt/25/)
$(document).ready(function () {
var divs = $('div');
var patt = /^\d\./;
var match = null;
for (i = 0; i < divs.length; i++) {
match = ($(divs[i]).text().match(patt));
$(divs[i]).text($(divs[i]).text().replace(match[0], "5."));
}
});
HTML
<div>1. peppers</div>
<div>2. eggs</div>
<div>3. pizza</div>
This works exactly the way I want it, but I want to add some of the content dynamically, but when I try to change the content of the copied divs, nothing happens.
Please refer to this fiddle:
http://jsfiddle.net/8ohzayyt/24/
I have put some comments, to be more clear what I want to achieve.
I thing that your problem is that you're not passing an element to your changeLabel function, but just a string.
Look at this solution: http://jsfiddle.net/8ohzayyt/26/
Here is the line I changed to make your code work:
var newContent = $("<hr/><div id='destination'>" + $("#holder").html() + "</div>");
I just wrapped your HTML in $(). this creates an element from the string.
try:
var newContent = $("<hr/><div id='destination'>" + $("#holder").html() + "</div>");
EDIT:
Brief explanation What I've done.
In order to make $(el).find('div'); work changeLabel() needs an element. Instead of passing newContent as a string doing the above will make it pass as an element which will make $(el).find('div'); work.

Adding div element to body or document in JavaScript

I am creating a light box in pure JavaScript. For that I am making an overlay. I want to add this overlay to body but I also want to keep the content on the page. My current code adds the overlay div but it also removes the current contents in body. How to add div element and keep contents on body?
var el = document.getElementById('element');
var body = document.getElementsByTagName('body');
el.innerHTML = '<p><a id="clickme" href="#">Click me</a></p>';
document.getElementById('clickme').onclick = function (e) {
e.preventDefault();
document.body.innerHTML = '<div style="position:absolute;width:100%;height:100%;opacity:0.3;z-index:100;background:#000;"></div>';
}
Using Javascript
var elemDiv = document.createElement('div');
elemDiv.style.cssText = 'position:absolute;width:100%;height:100%;opacity:0.3;z-index:100;background:#000;';
document.body.appendChild(elemDiv);
Using jQuery
$('body').append('<div style="position:absolute;width:100%;height:100%;opacity:0.3;z-index:100;background:#000;"></div>');
Try this out:-
http://jsfiddle.net/adiioo7/vmfbA/
Use
document.body.innerHTML += '<div style="position:absolute;width:100%;height:100%;opacity:0.3;z-index:100;background:#000;"></div>';
instead of
document.body.innerHTML = '<div style="position:absolute;width:100%;height:100%;opacity:0.3;z-index:100;background:#000;"></div>';
Edit:-
Ideally you should use body.appendChild method instead of changing the innerHTML
var elem = document.createElement('div');
elem.style.cssText = 'position:absolute;width:100%;height:100%;opacity:0.3;z-index:100;background:#000';
document.body.appendChild(elem);
Instead of replacing everything with innerHTML try:
document.body.appendChild(myExtraNode);
improving the post of #Peter T, by gathering all solutions together at one place.
Element.insertAdjacentHTML()
function myFunction() {
window.document.body.insertAdjacentHTML( 'afterbegin', '<div id="myID" style="color:blue;"> With some data...</div>' );
}
function addElement(){
var elemDiv = document.createElement('div');
elemDiv.style.cssText = 'width:100%;height:10%;background:rgb(192,192,192);';
elemDiv.innerHTML = 'Added element with some data';
window.document.body.insertBefore(elemDiv, window.document.body.firstChild);
// document.body.appendChild(elemDiv); // appends last of that element
}
function addCSS() {
window.document.getElementsByTagName("style")[0].innerHTML += ".mycss {text-align:center}";
}
Using XPath find the position of the Element in the DOM Tree and insert the specified text at a specified position to an XPath_Element. try this code over browser console.
function insertHTML_ByXPath( xpath, position, newElement) {
var element = document.evaluate(xpath, window.document, null, 9, null ).singleNodeValue;
element.insertAdjacentHTML(position, newElement);
element.style='border:3px solid orange';
}
var xpath_DOMElement = '//*[#id="answer-33669996"]';
var childHTML = '<div id="Yash">Hi My name is <B>\"YASHWANTH\"</B></div>';
var position = 'beforeend';
insertHTML_ByXPath(xpath_DOMElement, position, childHTML);
The most underrated method is insertAdjacentElement.
You can literally add your HTML using one single line.
document.body.insertAdjacentElement('beforeend', html)
Read about it here - https://developer.mozilla.org/en-US/docs/Web/API/Element/insertAdjacentElement
The modern way is to use ParentNode.append(), like so:
let element = document.createElement('div');
element.style.cssText = 'position:absolute;width:100%;height:100%;opacity:0.3;z-index:100;background:#000;';
document.body.append(element);
You can make your div HTML code and set it directly into body(Or any element) with following code:
var divStr = '<div class="text-warning">Some html</div>';
document.getElementsByTagName('body')[0].innerHTML += divStr;
Try doing
document.body.innerHTML += '<div style="position:absolute;width:100%;height:100%;opacity:0.3;z-index:100;background:#000;"></div>'
The best and better way is to create an element and append it to the body tag.
Second way is to first get the innerHTML property of body and add code with it. For example:
var b = document.getElementsByTagName('body');
b.innerHTML = b.innerHTML + "Your code";
Here's a really quick trick:
Let's say you wanna add p tag inside div tag.
<div>
<p><script>document.write(<variablename>)</script></p>
</div>
And that's it.

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