Before, not replace - javascript

Trying to figure out how should I put a span before my_div_class and not to replace all of it. Now it replaces the div, but I don't want to do it. I assume it's something like :before but have no idea how to use it.
<script>
{
var x = document.getElementsByClassName("my_div_class");
x[0].innerHTML = "<span style='color:#ff0000;'>Hello World!<span>";
}
</script>

Use insertAdjacentHTML:
var x = document.getElementsByClassName("my_div_class");
var html = '<span style="color:#ff0000;">Hello World!<span>';
x[0].insertAdjacentHTML('beforebegin', html);
<div class="my_div_class">Hallo</div>

If you want to add the span before the current content of the div, use:
x[0].innerHTML = "<span style='color:#ff0000;'>Hello World!</span> " + x[0].innerHTML;
Notice that you have several errors in your code:
You didn't close the span tag properly.
You don't need those curly brackets.
You may want to add a space at the end of the span to separate it from the current content of the div.
Try this:
var x = document.getElementsByClassName("my_div_class");
x[0].innerHTML = "<span style='color:#ff0000;'>Hello World!</span> " + x[0].innerHTML;
<div class="my_div_class">first div</div>
<div class="my_div_class">another div</div>
<div class="my_div_class">yet another div</div>
<div class="my_div_class">second div</div>
<div class="my_div_class">third div</div>

Related

How to insertAdjacentHTML between 2 different divs

I need to get my div between 2 divs inside my template. I can only edit it with external HTML, JS.
Template looks like this:
<main id="content-in">
<div id="homepage-banner"> XXX </div>
<div id="carousel-banner"> XXX </div>
And I need to get my img and a href <div id="moveOut"> XXX </div> between these 2.
I have it like this now which works ok:
<script>
function addCode() {
var d1 = document.getElementById('content-in');
d1.insertAdjacentHTML('afterbegin', '<div id="moveOut"><img src="https://example.png" alt=""></div>');
}
</script>
but I need to move it.
Thank you for your help.
You need to insert after the homepage-banner DIV.
var d1 = document.getElementById("homepage-banner");
d1.insertAdjacentHTML('afterend', '<div id="moveOut"><img src="https://example.png" alt=""></div>');

Change Class Content to href

<div class="container">
<span class="text1">test</span>
<span class="text2">test</span>
</div>
I want to change "text2" to a href in a javascript inside my function like this:
var x=document.getElementsByClassName("text2"); // Find the elements
x.innerHTML="<a href='https://test.com'>test</a>"; // Change the content
so the content of "text2" changes to a hyperlink called "test" which refers to "https://test.com"
you can do it like so:
var element = document.querySelector(".text2"); // Find the first element with the class text2
element.innerHTML = "test"; // Change the content including all HTML elements that might be in there to the value specified escaping the " character
<div class="container">
<span class="text1">test</span>
<span class="text2">test</span>
</div>
the problem was you didn't escaped the " character
you can do it also without the escaping like that:
var element = document.querySelector(".text2"); // Find the first element with the class text2
element.innerHTML = "<a href='https://test.com'>test</a>"; // Change the content including all HTML elements that might be in there to the value specified
<div class="container">
<span class="text1">test</span>
<span class="text2">test</span>
</div>
Not quite sure which approach you need. So here are both:
HTML
<div class="container">
<span class="text1">test</span>
<span class="text2">test</span>
</div>
Approach A - Replace the inner html of the target
document.querySelector(".text2").innerHTML = "<a href='https://test.com'>test</a>";
Approach B - Replace the Span with Anchor
var target = document.querySelector(".text2");
if (target) {
var anchor = document.createElement("a");
anchor.setAttribute("href", "https://www.test.com");
anchor.innerHTML = target.innerHTML;
target.replaceWith(anchor);
}

How to add a div between two divs by Javascript

I am using wordpress and I want to add some html code on page using Javascript. I don't want to make child theme then edit php files. It is risky and I don't know about php.
I want to add a sibling div. This is an example code as default.
<div class="div1">
<div class="div1inside">
Text
</div>
</div>
<div class="div2">
<div class="div2inside">
Text
</div>
</div>
Now I want to add my custom div and its inside html between both div1 and div2.
<div class="mydiv">
<div class="mydivinside">
Text
</div>
</div>
Please let me know how is it possible using Javascript.
There are (at least) two ways, the first:
// document.querySelector() finds, and returns, the first element
// matching the supplied selector (or null, if no element is found):
var el1 = document.querySelector('.div1');
// here we create an adjacent element from the string of HTML,
// the 'afterend' argument states that this adjacent element
// follows the el1 node, rather than preceding it or appearing
// within:
el1.insertAdjacentHTML('afterend', '<div class="mydiv"><div class="mydivinside">Text</div></div>');
var div1 = document.querySelector('.div1');
div1.insertAdjacentHTML('afterend', '<div class="mydiv"><div class="mydivinside">Text</div></div>');
<div class="div1">
<div class="div1inside">
Text
</div>
</div>
<div class="div2">
<div class="div2inside">
Text
</div>
</div>
And the second where you first create that <div> to be inserted, and then use parentNode.insertBefore():
var htmlString = '<div class="mydiv "><div class="mydivinside">Text</div></div>',
// here we create a <div> element:
div = document.createElement('div'),
// we retrieve the element after which the new
// element should be inserted:
div1 = document.querySelector('.div1');
// assign the supplied HTML string to the innerHTML of the
// created element:
div.innerHTML = htmlString;
// and use parentNode.insertBefore to insert the desired element
// (the first argument) before the element identified in the
// second argument, which is the nextSibling of the found
// 'div1' element:
div1.parentNode.insertBefore(div.firstChild, div1.nextSibling);
var htmlString = '<div class="mydiv "><div class="mydivinside">Text</div></div>',
div = document.createElement('div'),
div1 = document.querySelector('.div1');
div.innerHTML = htmlString;
div1.parentNode.insertBefore(div.firstChild, div1.nextSibling);
<div class="div1">
<div class="div1inside">
Text
</div>
</div>
<div class="div2">
<div class="div2inside">
Text
</div>
</div>
References:
document.createElement().
document.querySelector().
Element.insertAdjacentHTML().
Node.firstChild.
Node.insertBefore().
Node.nextSibling.
Node.parentNode.
Use Node#insertBefore method.
// create a div element
var div = document.createElement('div');
// set class name
div.className = 'mydiv';
// set html contents
div.innerHTML = ' <div class="mydivinside"> Text </div>';
// get .div2 element
var ele = document.querySelector('.div2');
// insert before the .div2 element by getting
// its parent node
ele.parentNode.insertBefore(div, ele);
<div class="div1">
<div class="div1inside">
Text
</div>
</div>
<div class="div2">
<div class="div2inside">
Text
</div>
</div>
You can just use the before method to append a div between both div1 and div2. Here is the example:
$('.div2inside').before("<div class='mydiv'><div class='mydivinside'>Text</div></div>");
You could do something like this?
var firstDiv = document.getElementById('div1');
firstDiv.parentNode.insertBefore(document.getElementById('new-div'), firstDiv.nextSibling);
This however assumes that your new-div is already in the dom.
EDIT: to create a the new-div on the fly you can use #david-thomas's solution https://stackoverflow.com/a/41425079/1768337
This link will be helpfull to get the above result.
https://plainjs.com/javascript/manipulation/insert-an-element-after-or-before-another-32/

How parse DOM to get emails Javascript

I'am building a Chrome extension that parses the entire DOM/HTML and replace any found email(multiple emails) with the following div:
<div class="email_tmp"> found_email <span>SAVE EMAIL</span></div>
EXAMPLE:
<body>
<div>Some Text...</div>
<div>text a#a.com text</div>
<div>Some Text...</div>
<p>More Text</p>
<div><div><span>text b#b.com text</span></div></div>
<span>Last text</span>
</body>
replaced to:
<body>
<div>Some Text...</div>
<div>text <div class="email_tmp"> a#a.com <span>SAVE EMAIL</span></div> text</div>
<div>Some Text...</div>
<p>More Text</p>
<div><div><span>text <div class="email_tmp"> b#b.com <span>SAVE EMAIL</span></div> text</span></div></div>
<span>Last text</span>
</body>
How can I search and replace the found email by the entire div and the string found_email by the email too?
I want to replace only the found email(s) string, nothing more...
I really appreciate any help.
Here is the total solution for what your looking for
HTML
<div id="main">
sdfsdsdfsdfsdf a#a.com sdfsdfsdfsdfsdfsdf
</div>
JavaScript
var page_content = document.getElementById('main').innerHTML;
var found_email = "<div class='email_tmp'> found_email <span>SAVE EMAIL</span></div>";
//gives an array of the emails
var email = page_content.match(/([a-zA-Z0-9._-]+#[a-zA-Z0-9._-]+\.[a-zA-Z0-9._-]+)/gi);
//replaces the emails to your desired content
var result = page_content.replace(email, found_email);
//replaces the changed HTML back to the 'main' div
document.getElementById('main').innerHTML = result;
Here is the Fiddle
Update:
If you want to replace only the text without adding any class or tags to the content of the HTML, then it gets real complicated to write a vanilla script for the same. In that case I would highly suggest you to use this library which I found to be the perfect solution for your problem.
Its a library called findAndReplaceDOMText which uses inbuilt methods to solve the purpose. You just need to give the find(what to find) and replace(replacing HTML) like so,
findAndReplaceDOMText(document.getElementById('t'), {
find: /([a-zA-Z0-9._-]+#[a-zA-Z0-9._-]+\.[a-zA-Z0-9._-]+)/gi,
replace: '<div class='email_tmp'> found_email <span>SAVE EMAIL</span></div>'
});
You can obviously revert if you face any problems in implementing this library.
Also this a must read article for you - replacing-text-in-the-dom-solved
Slight update on #NikhilNanjappa 's original answer: my version is less efficient, but it will keep the actual email address and prepend the div and append the span and closing tags, based on the original answer.
var save_email_beg = "<div class='email_tmp'> ";
var save_email_end = " <span>SAVE EMAIL</span></div>";
var i = 0;
for (; i < email.length; i++) {
var new_string = save_email_beg + email[i] + save_email_end;
page_content = page_content.replace(email[i], new_string);
}
document.getElementById('main').innerHTML = page_content;

javascript image rollover inside div

i have a single div 100px X 300px. What's the easiest way in JavaScript so when I hover over the div i show an image and then when i leave the div the image disappears.
for starters i thought the following would get me started but i can't seem to remove the image properly
<script type="text/javascript">
function MouseOver_Event(elementId) {
var imgToCreate = document.createElement('img');
imgToCreate.setAttribute('id', 'imgHandle');
imgToCreate.setAttribute('src', elementId + '.png');
imgToCreate.setAttribute('onmouseout', 'MouseOut_Event('+elementId+')');
var targetDiv = document.getElementById(elementId);
targetDiv.appendChild(imgToCreate);
targetDiv.removeAttribute('onmouseover', 'MouseOver_Event');
}
function MouseOut_Event(elementId) {
var imgToRemove = document.getElementById('imgHandle');
var targetDiv = imgToRemove.parentNode();
if (imgToRemove != null)
targetDiv.removeChild(imgToRemove);
targetDiv.setAttribute('onmouseover', 'MouseOut_Event(' + elementId + ')');
}
</script>
</head>
<body>
<div id="div1" onmouseover="MouseOver_Event(this.id)"></div>
<div id="div2" onmouseover="MouseOver_Event(this.id)"></div>
<div id="div3" onmouseover="MouseOver_Event(this.id)"><img src="Div3.png" alt="test" onmouseout="MouseOut_Event(parentNode's id or something)" /></div>
</body>
You're attaching your MouseOut_Event to onmouseover instead of onmouseout. But you probably don't need to be messing with dynamic event creation anyway; just add onmouseout="MouseOut_Event(this.id)" to the three divs and that should do it.
Why don't you use CSS instead ?
For example:
#div1{background:none;}
#div1:hover{background:url('src/div1.png') no-repeat;}

Categories

Resources