I have this code:
<div class="input">
<input type="number" id="myID" oninput="myFunction()">
<div>
<h3>MY TEXT</h3>
</div>
</div>
and I want to make a javascript code to remove the div below the input field whenever I write anything in the input
..........
I tried this code:
function myFunction(){
var field = document.getElementById("myID");
var num = field.value;
var parent = field.parentNode;
parent.innerHTML = field.outerHTML;
field.value = num;
}
but it have a problem each time I make an input, I have to re-click inside the input to make it active again
check out the code here
You should not use inline HTML event attributes to wire up event handlers. That technique is 25+ years old and will not die the death it deserves because people just keep copying it from other code they've seen.
See the comments for the simple explanation:
// Add the event handler to the input in JavaScript, not in HTML
document.getElementById("myID").addEventListener("input", removeElement);
function removeElement(){
// Remove the sibling element that follows the input
document.querySelector("#myID").nextElementSibling.remove();
// Now that the element has been removed, this function is no
// longer required, so remove the event handler to prevent attempts
// to remove it again when it's no longer there. "this" refers to
// the object that caused this function to be invoked (the input
// element in this case).
this.removeEventListener("input", removeElement);
}
<div class="input">
<input type="number" id="myID">
<div>
<h3>MY TEXT</h3>
</div>
</div>
How to remove an HTML element using JavaScript ?
Given an HTML element and the task is to remove the HTML element from the document using JavaScript.
Approach:
Select the HTML element which need to remove.
Use JavaScript remove() and removeChild() method to remove the
element from the HTML document.
Exemple to remove a div :
div.parentNode.removeChild(div);
Follow this link for more information.
I hope I was able to help you.
<div class="input">
<input type="number" id="myID" >
<div id="id2">
<h3>MY TEXT</h3>
</div>
</div>
<script>
document.getElementById("myID").oninput = function() {myFunction()};
function myFunction() {
document.getElementById("id2").innerHTML="";
}
</script>
Problem with using innerHTML is you are basically using a whiteboard. You erase everything on it and you have to redraw it all. That means you would need to reset the value and focus. It is doable, just not practical.
The better thing to do would be to select the element and remove it with .remove()
var field = document.getElementById("myID");
var num = field.value;
if (num.length) {
field.nextElementSibling.remove()
}
It will work, but you will be better off using a class to hide the element. It also has the benefit that if the user deletes the text in the input, you can reshow the message. I would just hide it with a css class with toggle. I would select the div with nextElementSibling.
function myFunction(){
var field = document.getElementById("myID");
var num = field.value;
field.nextElementSibling.classList.toggle('hidden', num.length)
}
.hidden {
display: none;
}
<div class="input">
<input type="number" id="myID" oninput="myFunction()">
<div>
<h3>MY TEXT</h3>
</div>
</div>
Related
I am trying to click a button but the only thing that defines it is multiple classes. The element I want to click is
<div class="U26fgb XHsn7e obPDgb M9Bg4d">This is a button </div>
How would I go about clicking it using Javascript?
As long as it is the only <div> element with that class combination, you'd use .querySelector(), which accepts any valid CSS selector as an argument so you can select elements in JavaScript the same way you would in CSS:
// Scan the document for the <div> that has the required classes
let theDiv = document.querySelector("div.U26fgb.XHsn7e.obPDgb.M9Bg4d");
// Set up a click event handling function
theDiv.addEventListener("click", function(){
console.log("you clicked me");
});
// Trigger the click event of the <div>
theDiv.click();
<div class="U26fgb XHsn7e obPDgb M9Bg4d">Click Me</div>
FYI: You should get out of the habit of putting spaces on the insides of the < and > delimiters in HTML. Use this:
<div class="U26fgb XHsn7e obPDgb M9Bg4d">Click Me</div>
Not this:
< div class="U26fgb XHsn7e obPDgb M9Bg4d" >Click Me< /div >
very simple with jQuery:
$(".U26fgb.XHsn7e.obPDgb.M9Bg4d").click(function(){
console.log("clicked!");
});
const div = document.querySelector('div .M9Bg4d');
div.addEventListener("click", ()=> {
// here put what you wanna do after clicking the div.
});
onclick attribute works well inside almost all the html tags and here is the simple solution to click on the div and get a result. All the Best!
function clickDiv(){
console.log("Div is Clicked");
}
<div class="U26fgb XHsn7e obPDgb M9Bg4d" onclick="clickDiv()">This is a button </div>
I'm trying to find out if it's possible to clone an HTML div with JS, edit it and append it again as a new element. So my source is, for example, this code here:
<div class="wrapper">
<div class="element">
<input id="test--1" value="ABC"/>
</div>
</div>
After copying this element, I need to find a way to change the attribute id of the new cloned input, clear the input value and paste it again in the wrapper so that it looks like this at the end:
<div class="wrapper">
<div class="element">
<input id="test--1" value="ABC"/>
</div>
<div class="element">
<input id="test--2" value=""/>
</div>
</div>
Does that make sense to you? If yes, how can I get this done? Or is it better to assign the content to a variable to append it? I'm looking for the best way here and maybe my idea is a solution too.
You can use pure JavaScript to do this by just cloning the .element div using the cloneNode() method, assign new id and value to the clone div and finally append it back to the document using the insertBefore() method like this:
let x = document.querySelector(".element");
let y = x.cloneNode(true);
y.children[0].id = "test--2";
y.children[0].defaultValue = "";
x.parentNode.insertBefore(y, x.nextSibling);
<div class="wrapper">
<div class="element">
<input id="test--1" value="ABC"/>
</div>
</div>
JSFiddle with the above code: https://jsfiddle.net/AndrewL64/jvc7reza/18/
Based on this answer you could do like:
$('#cloneBtn').on('click', function() {
// get the last input having ID starting with test--
var $inp = $('[id^="test--"]:last'); // Or use :first if you need
// Get parent element
var $div = $inp.closest('.element');
// Create clone
var $div_clone = $div.clone();
// Retrieve number from ID and increment it
var num = parseInt($inp.prop("id").match(/\d+/g), 10) + 1;
// Generate new number and assign to input
$div_clone.find('[id^="test--"]').prop({id: 'test--' + num, value: ''});
// Insert cloned element
$div.after($div_clone); // Or use .before() if you need
});
.element {
padding: 10px;
outline: 2px solid #0bf;
}
<button id="cloneBtn">CLICK TO CLONE</button>
<div class="wrapper">
<div class="element">
<input id="test--1" value="ABC" />
</div>
</div>
Once done inspect the input elements to see the new IDs
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
Scrambled elements, retrieve highest ID, increment, clone, append.
If your numbered IDs are scrambled, we first need a way to retrieve the highest ID number. Here's an implementation in pure JavaScript:
function cloneElement () {
const inpAll = document.querySelectorAll('[id^="test--"]');
if (!inpAll.length) return; // do nothing if no elements to clone
const maxID = Math.max.apply(Math, [...inpAll].map(el => +el.id.match(/\d+$/g)[0]));
const incID = maxID + 1;
const element = document.querySelector('.element'); // Get one for cloning
const eleClone = element.cloneNode(true);
const inpClone = eleClone.querySelector('[id^="test--"]');
inpClone.id = 'test--'+ incID;
inpClone.value = incID; // just for test. Use "" instead
document.querySelector('.wrapper').prepend(eleClone);
}
document.querySelector('#cloneBtn').addEventListener('click', cloneElement);
.element {
padding: 10px;
outline: 2px solid #0bf;
}
<button id="cloneBtn">CLICK TO CLONE</button>
<div class="wrapper">
<div class="element">
<input id="test--1" value="1" />
</div>
<div class="element">
<input id="test--23" value="23" />
</div>
<div class="element">
<input id="test--7" value="7" />
</div>
</div>
Once done inspect the input elements to see the new IDs
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
I don't know what data you know, why you want to do such a thing but it can be done :-)
One way is like that:
const elemToCopy = document.getElementById("test--1").parentNode; // I assume you know id
const copiedElem = elemToCopy.cloneNode(true);
const newInput = copiedElem.querySelector("#test--1");
newInput.id = "test--2";
newInput.value = "";
elemToCopy.parentNode.append(copiedElem);
Let me know in a comment if something is not clear :-)
Yes, use jQuery's .clone().
Here is an example that might be relevant to your situation:
let newElement = $('.element').clone();
newElement.find('input').attr('id', 'test--2').val('');
$('.wrapper').append(newElement);
Explanation
In the first line, we created a new cloned element by using jQuery clone().
Then, we found it's child input, changed it's ID and reset the val().
Finally, we found the .wrapper element and appended the new cloned element to it.
I would like to check if the text exist in the div element, so that if text matches the text in div it will alert "hello". May I know how am I able to achieve this result? Thank you.
<script type="text/javascript">
jQuery(document).ready(function(){
var text = "div[style*=\"width: 550px;\"]";
if (#content.indexOf(text) > -1){
alert("Hello");
}
});
</script>
<div id="content">
<div style="width:550px;">James</div>
<div style="width:500px;">Amy</div>
</div>
Here you go with a solution https://jsfiddle.net/9kLnvyqm/
if($('#content').text().length > 0) { // Checking the text inside a div
// Condition to check the text match
if($('#content').text().indexOf('Amy')){
console.log('Hello');
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="content">
<div style="width:550px;">James</div>
<div style="width:500px;">Amy</div>
</div>
If you want only the text content from a container then use text(), if you are looking for html content then use html().
Hope this will help you.
It is possible to get the value of inline style of an element.
var wid = $("#content > div")[0].style.width;
if(wid === "550px"){
//correct width detected. you can use alert instead of console.log
console.log("hello");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="content">
<div style="width:550px;">James</div>
<div style="width:500px;">Amy</div>
</div>
You have multiple elements inside #content. you may want to use the return value of
$('#content').children().length;
and loop the program to get inline width of all elements. Ping if you need some help with the loop
I'm trying to create a selector that will grab li element and show the text. The problem is that inside li tag I have span tag and that is also displayed.
How do I grab text of closest element without some of the elements inside?
see here, I don't want the word 'Edit' to be included.
http://jsfiddle.net/ozyf87tb/
<li>This is the story of the Jungle book
<form action="" method="" class="form_edit">
<textarea class="inte" value="" name="inte"></textarea>
</form>
<span class="edit">Edit</span>
</li>
$(".edit").click( function(ev) {
var a = $(this).closest('li').text();
$('.inte').val(a);
});
http://jsfiddle.net/ozyf87tb/7/
Clone it (so you work with the clone, not in the DOM), get children, remove the children, get the text.
$(".edit").click( function(ev) {
var a = $(this).closest('li').clone().children().remove().end().text();
$('.inte').val(a);
});
The most readable way to do what you want to do is surrounding your text with a container like <span class='myText'></span>. So you could select the exact container using its class :
DEMO
<li><span class='myText'>This is the story of the Jungle book</span>
<form action="" method="" class="form_edit">
<textarea class="inte" value="" name="inte"></textarea>
</form>
<span class="edit">Edit</span>
</li>
$(".edit").click( function(ev) {
var a = $(this).prevAll('.myText').text();
$('.inte').val(a);
});
First, get a clone() of the html.
var a = $(this).closest('li').clone();
Then remove the extraneous span.
a.find('span').remove();
Then put that into the textarea.
$('.inte').val( a.text() );
This can also be rewritten into a single string, but takes away from readability.
var a = $(this).closest('li').clone().find('span').remove().end().text();
$('.inte').val( a );
jsfiddle
Use contents() and then filter your selection to return only text nodes. Then all you need to do is to trim any white-space:
var a = $.trim($(this).closest('li').contents().filter(function(){
return this.nodeType == 3;
}).text());
JSFiddle
Documentation
$.trim()
.contents()
.filter()
Node.nodeType
I'm pulling a content from PHP array and I have a situation like this:
<div class="weight-display">
<span>04/25/2011</span> <span>100lbs</span> <span>Edit</span> <a href="http://foo.com">Delete</span>
</div>
<div class="weight-display">
<span>04/27/2011</span> <span>150lbs</span> <span>Edit</span> <a href="http://foo.com">Delete</span>
</div>
etc...
Now when somebody clicks on Edit within, let's say, first div where weight is 100lbs, I just need that "div" to change and to have input field instead of simple text where weight is (while others will remain the same) and to be like this:
<div class="weight-display">
<span>04/25/2011</span> <input type="text" value="100" /> <span>Save</span> <span>Cancel</span>
</div>
<div class="weight-display">
<span>04/27/2011</span> <span>150lbs</span> <span>Edit</span> <a href="http://foo.com">Delete</span>
</div>
etc..
So basically div has to "reload itself" and change content. Now I really need some very simple Javascript solution. Preferably I would like a solution with a hidden div beneath original one, so they just swap places when user clicks on EDIT and in a case if CANCEL is pressed to swap places again so original div with text is displayed...
Thanks,
Peter
<style type="text/css">
/* Normal mode */
.weight-display div.edit {display:none}
/* Editor mode */
.weight-edit div.show {display:none}
</style>
<div class="weight-display">
<button onclick="toggle(this)">Edit this!</button>
<div class="edit"><input type="text" value="Test" /></div>
<div class="show">Test</div>
</div>
<script type="text/javascript">
function toggle(button)
{
// Change the button caption
button.innerHTML = button.innerHTML=='Edit this!' ? 'Cancel' : 'Edit this!';
// Change the parent div's CSS class
var div = button.parentNode;
div.className = div.className=='weight-display' ? 'weight-edit' : 'weight-display';
}
</script>
What you suggest is basically correct. I would generate two div's one for display and one edit. The edit div will initially have display: none. When the Edit is clicked, hide the display div and show the edit div.
How about something like:
onClick event calls a function (EDITED to be a little smarter than my original brute force method):
function swapdivs ( id_of_topdiv, id_of_bottomdiv ) {
var topdiv = getRefToDiv( id_of_topdiv );
var bottomdiv = getRefToDiv( id_of_bottomdiv );
var temp = topdiv.style.zIndex;
topdiv = bottomdiv.style.zIndex;
bottomdiv = temp.style.zIndex;
}
Could that or similar work for you? Or am I missing some subtle yet crucial requirement?