Why Node.removeChild(Old Child) doesn't works in functions? - javascript

i have a button when i click it i want to print hello plus the innerHTML of the button and remove itself :
<script type="text/javascript">
function MyFunc(element) {
var parentNd = element.parentElement
parentNd.innerHTML += "<p>Hello</p>" + element.innerHTML
parentNd.removeChild(element)
}
</script>
<button onclick="MyFunc(this);">My Button</button>
but it's just print the text and don't remove itself
why?

By rewriting the parent's innerHTML, you're replacing the button with a copy (since the HTML that defines the button is parsed again). So your reference to element points to a button that is no longer in the DOM, therefore removing it has no effect.
I suggest you stop using innerHTML, create the P element with createElement and then call replaceChild to swap it with the button.

this is okey!
<script type="text/javascript">
function MyFunc(element) {
var parentNd = element.parentElement
parentNd.removeChild(element)
parentNd.innerHTML += "<p>Hello</p>" + element.innerHTML
}
</script>
<button onclick="MyFunc(this);">My Button</button>

Use jquery
<button id="x" onclick="MyFunc(this);">My Button</button>
function MyFunc(element) {
var parentNd = element.parentElement
parentNd.innerHTML += "<p>Hello</p>" + element.innerHTML
$("#x").remove();
}
DEMO
OR use below code it will also works
function MyFunc(element) {
var parentNd = element.parentElement
document.write(element.innerHTML);
parentNd.removeChild(element);
}
Note: I didn't prefer this method , i think the best idea is hide the button in onclick event

Related

How to replace all of a certain string in html while keeping javascript attributes

I'm trying to replace a part of an HTML document using RegEx.
Take this example:
for (; document.body.innerHTML.indexOf(/ea/) != -1;) {
document.body.innerHTML = document.body.innerHTML.replace(/ea/, "x");
}
I eat food and read books.
But how would I replace part of the HTML tag (root element) and not remove anything?
(event listeners, etc)?
function x(e) {
return document.querySelector(e);
}
x("textarea").value = document.documentElement.outerHTML;
x("button").addEventListener("click", function() {
console.log("button pressed");
for (; document.body.innerHTML.indexOf(/the-language/) != -1;) {
document.body.innerHTML = document.body.innerHTML.replace(/the-language/, "x");
}
x("textarea").value = document.documentElement.outerHTML;
});
<!DOCTYPE html>
<html lang="the-language">
<p>the-language</p>
<p>There is a button with an event listener, and the HTML tag has the word I'm replacing. The event listener is removed and the root element (html) isn't changed.</p>
<button>Click me to replace and then show new content in textarea</button>
<p>the-language</p>
<textarea></textarea>
</html>
You want to change the attribute using setAttribute of course. You can:
document.querySelector("html").setAttribute('lang', 'other-lang');
Other than that, check out my recent answer about changing only text nodes. For example this one

How to delete text box along with button in JavaScript

I have a button when user clicks the button it create the text box along with remove button
but all the text boxes created with same id how we can delete the text box when clicks respective remove button
here My Code:
<body>
<button type="button" id="URLbtn" onclick="Createinput()"> + Add URL</button>
<div id="TextAreaBtn"></div>
<script>
function Createinput() {
var newdiv=document.createElement("div");
newdiv.id="test"
var Inputele=document.createElement("input");
Inputele.type="text";
Inputele.id="URLtxt"
newdiv.appendChild(btnele);
var btnele=document.createElement("button");
btnele.id="rmvbtn"
btnele.type="button"
btnele.innerHTML="-"
btnele.onclick=RemoveUrlBox()
newdiv.appendChild(btnele);
var element = document.getElementById("TextAreaBtn");
element.appendChild(newdiv);
}
function RemoveUrlBox() {}
</script>
</body>
i am getting following output
if user click 2 remove button only remove the second textbox and button
You need to select the wrapping div. Easiest way is to use remove() and use closest. No need to use the id..... You also need to remember ids need to be unique.
function createInput() {
var newDiv = document.createElement("div");
newDiv.className = 'group';
var inputElem = document.createElement("input");
inputElem.type = "text";
newDiv.appendChild(inputElem);
var btnElem = document.createElement("button");
btnElem.type = "button";
btnElem.textContent = "-";
btnElem.addEventListener("click", removeUrlBox);
newDiv.appendChild(btnElem);
var element = document.getElementById("TextAreaBtn");
element.appendChild(newDiv);
}
function removeUrlBox() {
this.closest('.group').remove();
}
<button type="button" id="URLbtn" onclick="createInput()"> + Add URL</button>
<div id="TextAreaBtn"></div>
This should do the trick:
const txtarea=document.getElementById('TextAreaBtn');
document.getElementById('URLbtn').onclick=()=>txtarea.innerHTML+=
'<div><input type="text" class="URLtxt"><button class="rmvbtn">-</button></div>';
txtarea.onclick=ev=>ev.target.className==="rmvbtn"&&ev.target.parentNode.remove()
<button type="button" id="URLbtn"> + Add URL</button>
<div id="TextAreaBtn"></div>
I replaced your id attributes with class attributes, as these don't need to be unique.
I reduced your script by using innerHTML instead of laboriously putting elements together with createElement(). This is a matter of opinion as both methods have their advantages.
I also used delegated event listener attachment for the removal buttons. This way you can get away with a single event listener on div.TextAreaBtn. The attached funcion will only trigger any action if the clicked element has class "rmvbtn".
Change
btnele.onclick=RemoveUrlBox()
to
btnele.addEventListener('click', function (e) {
// `this` is the button that was clicked no matter about the id
// `this.parentNode` is the div you want to remove
const nodeToRemove = this.parentNode;
nodeToRemove.parentNode.removeChild(nodeToRemove);
});

Append text into div element when click using jquery

Using the below code I append some input elements into the #cls div. But when I try to type inside the input also new input add. I only need new input when I click "click" text. Can anyone help me. Thank you
$('#cls').click(function() {
var add="<input type="text">"
$(#cls).append(add);
});
<div id="cls">click</div>
You need to see whether the click actually happened in the div
$('#cls').click(function(e) {
if ($(e.target).is(this)) { //or !$(e.target).is('input')
var add = '<input type="text">';
$(this).append(add);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="cls">click</div>
If you user .after() method instead of .append() the textbox would appear outside the #cls div and hence clicking the textbox wouldn't cause adding a new one.
Some code
$('#cls').click(function() {
var add="<input type='text'>";
$('#cls').after(add);
});
Try it out
Append your input to parent element:
var clicked= false;
$('#cls').click(function() {
if(!clicked){
var add="<input type='text'>";
$(this).parent().append(add);
clicked = true;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='cls'>click</div>
use jQuery's one method. it will register click handler only once.
$('#cls').one("click", function(e) {
var add = '<input type="text">';
$(this).append(add);
});

onClick replace javascript element, with new javascript element

What I am trying to figure out is how to make a button, that when you click, will replace itself with a textbox. I found this code on the W3Schools website, and can't figure out how to put javascript (or HTML) elements in.
<p>Click the button to replace "Microsoft" with "W3Schools" in the paragraph below:</p>
<p id="demo">Visit Microsoft!</p>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction() {
var str = document.getElementById("demo").innerHTML;
var res = str.replace("Microsoft", "W3Schools");
document.getElementById("demo").innerHTML = res;
}
</script>
</body>
</html>
<input type="text" name="textbox" value="textbox"><br>
In the end I want to be able to replace a button with the textbox I put outside the html tags
I would not suggest you the innerHTML replacement method.
Here are the steps where you can use replaceChild
Get the parent node of the selected element
use replaceChild
Here the code
// create the new element (input)
var textBox = document.createElement("input");
textBox.type = "text";
// get the button
var button = document.getElementById("demo");
// reference to the parent node
var parent = element.parentNode;
// replace it
parent.replaceChild(textBox, button);
On older browser you probably need a slighlty different solution.
var parent = button.parentNode;
var next = button.nextSibling;
// remove the old
parent.removeChild(button);
// if it was not last element, use insertBefore
if (next) {
parent.insertBefore(textBox, next);
} else {
parent.appendChild(textBox);
}
I ended up finding a code that works off of http://www.webdeveloper.com/forum/showthread.php?266743-Switch-Div-Content-Using-Javascript

What is wrong with my Javascript?

This is my jsfiddle(http://jsfiddle.net/mZGsp/). I was trying to answer a question here but my code won't work. Here is the code:
JS
var stateOfClick = null;
function initiateLine(){
document.getElementById('test').innerHtml = "Started";
}
function endLine(){
document.getElementById('test').innerHtml = "Line Ended";
}
function createLines(){
if(!stateOfClick) {
initiateLine();
stateOfClick = 1;
} else {
endLine();
}
}
HTML
<body>
<input type="text" id="test" onclick="createlines()">
</body>
A couple of things,
change createlines() to createLines (camel-case).
change <element>.innerHtml to <element>.value
Inside JSFiddle, don't wrap your code inside a function, as then createLines won't be global which it needs to be for the onclick to work.
Here's a working example.
Not even this simple example will work on jsFiddle. You need to attach the event listener with JavaScript:
document.getElementById("someElement").onclick = function() {
//Do stuff
}
For input element you must use the value attribute not the innerHTML field.
function initiateLine(){
document.getElementById('test').value = "Started";
}
also you've misspelled the innerHTML function (though not the primary problem). innerHTML is used for html elements that can contain other elements such as a div containg a p element. Input and option elements all have a value attribute that can be used to extract or set their values.

Categories

Resources