I am looking for a way to remove a text from a div, without removing the button inside.
Please see the image above.
The following code does not work because it removes the button too.
$(".input-group-append").empty();
OR
document.querySelector(".input-group-append").text = '';
document.querySelector(".input-group-append").innerHTML = '';
To remove the text, you can store the children selectors first and clear the parent with innerHTML='' and add that children selectors again.
const parent = document.querySelector(".input-group-append");
const childs = [];
for(let i = 0; i < parent.children.length; i ++) {
childs.push(parent.children[i]);
}
parent.innerHTML = '';
childs.forEach((item) => parent.appendChild(item));
<div class="input-group-append">
<button type="submit" class="btn btn-search">Submit Button</button>
Test Text
</div>
Since you are not planning to remove the button itself and just want to remove the text within the button, you must modify the seclector to direct towards the button itself and then use text or innerText property.
document.querySelector(".input-group-append > button").text = '';
// OR
document.querySelector(".input-group-append > button").innerText = '';
This will remove the text from within the button.
For this use case could probably just do,
el = document.querySelector('.input-group-append')
for (let i = 0;i<el.children.length;i++) {
if(el.childNodes[i].nodeType === 3) {
el.removeChild(el.childNodes[i])
}
}
This shoud remove all loose text from your div without touching elements:
var elements = $(".input-group-append *");
$(".input-group-append").html("");
elements.each(function(){
$(".input-group-append").append($(this)[0]);
});
Related
My question aims to find the simplest way for removing a child from a div element. In this case either Apple, Orange or Banana. Which means you can put the cursor on one of these words and then click delete child.
The only way Iam thinking is doing it in two steps:
Returning the index of the selected child with returnIndexOfChild() (custom built)
Using the removeChild method
I mean when you are having a big text java script engine has to loop through the whole text to find the index. Is there a more direct way like deleting anchorNode by selection object?
//html part
<div contentEditable="true" id="editableField"><b>Apple</b><i>Orange</i><b>Banana</b></div>
<button onclick="deleteChild()"> Delete</button>
//javascript part
var selection = document.getSelection();
myDiv = document.getElementById("editableField");
//Returns index of selected child (1)
function returnIndexOfChild(){
let i = 0;
for (i; i < myDiv.childNodes.length; i++){
if(selection.anchorNode.parentElement === myDiv.childNodes[i]){
console.log(i);
break;
};
}
return i;
}
//Removing Child(2)
function deleteChild (){
myDiv.removeChild(myDiv.childNodes[returnIndexOfChild()]);
}
You can just call remove() on the element itself
function deleteChild (){
const selection = document.getSelection();
selection.anchorNode?.parentElement?.remove();
}
<div contentEditable="true" id="editableField"><b>Apple</b><i>Orange</i><b>Banana</b></div>
<button onclick="deleteChild()"> Delete</button>
2 solutions:
//html part
<div contenteditable="true" id="editableField">
<li>Apple</li>
<li>Orange</li>
<li>Banana</li>
<li>potato</li>
<li>grape</li>
<li>egg</li>
<li>milk</li>
</div>
<input type="text" class="input" />
<button class="button">Delete</button>
<script>
const myDiv = document.querySelector("#editableField");
const input = document.querySelector(".input");
const btn = document.querySelector(".button");
// first way thanks to event bubbling
myDiv.addEventListener("click", (ev) => {
ev.target.remove();
});
// second way, by iterating through items
btn.addEventListener("click", () => {
// The "onclick="..." in the html is old solution, new and better is addEventListener(...)"
const myDivChildren = [...myDiv.children]; // The "..." is spread operator, "myDiv" is HTMLCollection, an array like object in orter ot iterate ovet it I created array by spreading it
const inputValue = input.value || myDivChildren.length - 1; // take input value if exist, if not then last index so remove last item
myDivChildren.forEach((el, i) => {
if (i == inputValue) {
el.remove(); // When indexes match then delete
}
return; // When indexes match then stop executing loop
});
input.value = "";
});
I got rid of getSelection(), it complicates removing items, do you care about using getSelection()? Should I use it in the answer?
I want to target a data-ref with a specific value and add an inline style="display:none;" to it.
How can this be achived? Can someone help me please?
This is how it looks:
<div data="{test-bubble}}" data-ref="bubbles[test-link.com/test]" class="bubbles" state="default">
</div>
I tried this but it does not work:
var bubbleremoval = document.querySelector('[data-ref="bubbles[test-link.com/test]"]')
bubbleremoval.style.display = "none";
"""Your code should work if you are applying to a single element since query selector returns one element but for several elements you could fetch by classname and loop through the elements and remove display for each"""
var bubbleremoval = document.getElementsByClassName('bubbles')
for (let i = 0; i < bubbleremoval.length; i++) {
bubbleremoval[i].style.display = "none";
}
I'm creating a webpage which would collect links from the user and simply open every link in a new tab. For collecting links I am using HTML's <textarea> tag with a submit button.
User is expected to give only one link for each line
https://google.com
https://stackoverflow.com
https://facebook.com
I would open links by sending each passing each URL through this function.
function open(url) {
var open= window.open(url, '_blank');
open.focus();
}
But how exactly to run loop? How to get values from textarea in an array and then run a loop which would send value at every index to this function?
If you think this could be done in a better than other than this, feel free to add your method.
It would help if you gave your textarea a unique identifier, this way we can get at its contents easily. i.e, <textarea id="linksInput">...</textarea>
Then we can do
let links = document.getElementById("linksInput").value.split("\n");
We get the value in the textarea and split it at every newline character ("\n"), getting our individual links in an array, with each element being a single line from the original textarea value. Now we can loop through the array links.
for (let i = 0; i < links.length; i++) {
open(links[i]);
}
You can use the below code to get your result.
HTML
<textarea id='links'>
</textarea>
<button id='trigger'> Get value </button>
JS
document.addEventListener('DOMContentLoaded', () =>{
const ta = document.getElementById('links')
const button = document.getElementById('trigger')
button.addEventListener('click', () => {
const list = ta.value.split('\n')
forEach(let i=0; i < list.length; i++) {
window.open(list[0], "_blank");
}
})
})
You can add an id to the text field and use javascript to get the value of TextArea.
Since you are looking at multiple values separated by "/n", you will have to split the text and loop over the result.
function submitText() {
var textVal = document.getElementById("txtarea").value;
textVal = textVal.split('\n');
if (textVal.length > 0) {
for (const element of textVal) {
console.log(element);
window.open(element, "_blank");
}
}
}
<textarea id="txtarea"></textarea>
<button type="button" onclick="submitText()">Submit</button>
I have the next element:
<div id = "mydiv">
abc
<span>123</span>
</div>
document.getElementById('mydiv').textContent returns me: abc123
I want to get only the text of mydiv ('abc'). so I wonder if there is an option to use jquery in order to get it? maybe get all the content of an element except for span element..
and then getting his text..
p.s. I know I can wrap abc in span and then get it, but I wonder if there is another option to do it without changing my element..
DEMO JSFIDDLE
Try this ,
console.log($("#mydiv").clone() .children().remove().end().text());
You must select yours DIV by ID, then run through its "childrens" property and check their nodeType (textNodes has 3);
var div = document.getElementById("mydiv");
var result = "";
for(var i = 0; i < div.length; i++){
var node = div[i];
if( node.nodeType === 3 ){
result += node.data;
}
}
console.log(result);
Since you've included jQuery you can do this
var p = $('#mydiv').clone();
p.find('span').remove();
console.log(p.text());
DEMO
Using jQuery:
$(document).ready(function() {
alert($('#mydiv span').text());
});
If you expect to have more html elements inside your div, user regular expression to extract plain text after getting whole html content from div.
var re = /<.+>/;
var str = "abc<span>123</span>";
var newstr = str.replace(re, "");
Should give "abc"
How can i remove the style class applied to a textbox on the click event? I'm calling the textbox element using getElementsByName(). Here's my code:
<input id="userNameExists" name="popUpText" class="pop-upText" onclick="clearText(this);" />
function clearText(element)
{
id = element.getAttribute("id");
var textElement = document.getElementById(id);
textElement.value = "";
var element = document.getElementsByName("popUpText");
var count = 0;
for (count = 0; count < 2; count++) {
var id = element.item(count);
id.classname = "";
}
}
In the above script, im not getting the id in the variable id. Right now the values are like "#inputTextBoxName". Please help.
you can use removeClass();
you can manege your styling using attr();
exp:
$("#yourid").attr("style","float: right");
or remove class using
$("#yourid").removeClass("yourClass");
It is case sensitive so
id.className = '';
If you're trying to remove the class from the textbox when you click on the textbox itself, that code is far, far longer than it needs to be.
HTML:
<input type="text" id="userNameExists" name="popUpText" class="pop-upText" onclick="clearText(this);" />
Javascript:
<script>
function clearText(element) {
element.className = '';
element.value = '';
}
</script>
That said, inline event handlers (ie. declaring an onclick attribute on your HTML element) are a bad practice to get into.
Also, if you pass in a reference to an element, get its id, then call document.getElementById() with said id, you end up with two references to the same element. Yes, it should work, but totally pointless.