Remove <p class="classname"> in Javascript? - javascript

How can i remove this <p> tag with all its content in javascript?
say i have this html code
<p class="classname">
<input name="commit" value="Get Value" type="submit"> <span>or Cancel</span>
</p>
Now i need to replace/remove it in javascript, does anyone know how i can remove it?

Assuming you don't want to change the markup: The easiest way is to use a library. e.g. with jQuery:
jQuery('.classname').remove();
Otherwise, you need to get a reference to the element and then:
el.parentNode.removeChild(el);
Getting a reference to the element is the tricky part. Some browsers implement getElementsByClassName, but you'll have to write your own or use a third party implementation for the rest.
if (!document.getElementsByClassName) {
document.getElementsByClassName = function (className) {
/* ... */
}
}
If you are willing to change the markup, then give the element an id and use document.getElementById to get the reference to it.

If you have to do it in plain javascript it'll be painful because of Internet Explorer which doesn't support getElementsByClassName() (maybe in newer version ?).
var elems = document.getElementsByTagName('p');
var elemsLenght = elems.lenght;
for (var i = 0; i < elemsLenght; ++i) {
{
if (elems[i].className == 'classname')
{
elems[i].innerHTML = '';
}
}
But if you can, use a library/framework like jQuery, prototype, dojo, etc..

Try this:
<p id="someid">
<input name="commit" value="Get Value" type="submit"> <span>or Cancel</span>
</p>
function removeElement(id) {
var d = document.getElementById('myDiv');
var olddiv = document.getElementById(id);
d.removeChild(olddiv);
}
removeElement('someid');
With JQuery if you Want
$('p.classname').remove();

Related

How do I change more than one element?

EDIT: I changed the var to class but I might have some error in here.
Here it goes, I want to have this paragraph in which the user can change the name on the following paragraph. The code I'm using only changes one name but the rest remains the same.
<script type="text/javascript">
function changey(){
var userInput = document.getElementById('userInput').value;
var list = document.getElementByClassName('kiddo');
for (let item of list) {
item.innerHTML = userInput;
}
}
</script>
<input id="userInput" type="text" value="Name of kid" />
<input onclick="changey()" type="button" value="Change Name" /><br>
Welcome to the site <b class="kiddo">dude</b> This is how you create a document that changes the name of the <b class="kiddo">dude</b>. If you want to say <b class="kiddo">dude</b> more times, you can!
No error messages, the code only changes one name instead of all three.
Use class="kiddo" instead of id in the html.
You can then use var kiddos = document.getElementsByClassName('kiddo') which will return an array of all the elements of that class name stored in kiddos.
Then you just need to loop through the values and change what you want.
Example of loop below:
for (var i = 0; i < kiddos.length; i++) {
kiddos[i].innerHTML = userInput;
}
id should be unique on the page. Javascript assumes that there is only one element with any given id. Instead, you should use a class. Then you can use getElementsByClassName() which returns an entire array of elements that you can iterate over and change. See Select ALL getElementsByClassName on a page without specifying [0] etc for an example.
Hello You should not use id, instead use class.
Welcome to the site <b class="kiddo">dude</b> This is how you create a document that changes the name of the <b class="kiddo">dude</b>. If you want to say <b class="kiddo">dude</b> more times, you can!
After That on Js part :
<script type="text/javascript">
function changey(){
var userInput = document.getElementById('userInput').value;
var list = document.getElementByClassName('kiddo');
for (let item of list) {
item.innerHTML = userInput;
}
}
</script>
you should use class instated of id. if you use id then the id [kiddo] must be unique
In short, document.querySelectorAll('.kiddo') OR
document.getElementsByClassName('kiddo') will get you a list of elements to loop through. Take note of querySelectorAll, though - it uses a CSS selector (note the dot) and doesn't technically return an array (you can still loop through it, though).
See the code below for some full working examples (const and arrow functions are similar to var and function, so I'll put up a version using old JavaScript, too):
const formEl = document.querySelector('.js-name-change-form')
const getNameEls = () => document.querySelectorAll('.js-name')
const useNameFromForm = (formEl) => {
const formData = new FormData(formEl)
const nameValue = formData.get('name')
const nameEls = getNameEls()
// Set the text of each name element
// NOTE: use .textContent instead of .innerHTML - it doesn't get parsed, so it's faster and less work
nameEls.forEach(el => el.textContent = nameValue)
}
// Handle form submit
formEl.addEventListener('submit', (e) => {
useNameFromForm(e.target)
e.preventDefault() // Prevent the default HTTP request
})
// Run at the start, too
useNameFromForm(formEl)
.name {
font-weight: bold;
}
<!-- Using a <form> + <button> (submit) here instead -->
<form class="js-name-change-form">
<input name="name" value="dude" placeholder="Name of kid" />
<button>Change Name</button>
<form>
<!-- NOTE: Updated to use js- for js hooks -->
<!-- NOTE: Changed kiddo/js-name to spans + name class to remove design details from the HTML -->
<p>
Welcome to the site, <span class="js-name name"></span>! This is how you create a document that changes the name of the <span class="js-name name"></span>. If you want to say <span class="js-name name"></span> more times, you can!
</p>
var formEl = document.querySelector('.js-name-change-form');
var getNameEls = function getNameEls() {
return document.querySelectorAll('.js-name');
};
var useNameFromForm = function useNameFromForm(formEl) {
var formData = new FormData(formEl);
var nameValue = formData.get('name');
var nameEls = getNameEls(); // Set the text of each name element
// NOTE: use .textContent instead of .innerHTML - it doesn't get parsed, so it's faster and less work
nameEls.forEach(function (el) {
return el.textContent = nameValue;
});
};
// Handle form submit
formEl.addEventListener('submit', function (e) {
useNameFromForm(e.target);
e.preventDefault(); // Prevent the default HTTP request
});
// Run at the start, too
useNameFromForm(formEl);
<button class="js-get-quote-btn">Get Quote</button>
<div class="js-selected-quote"><!-- Initially Empty --></div>
<!-- Template to clone -->
<template class="js-quote-template">
<div class="js-quote-root quote">
<h2 class="js-quote"></h2>
<h3 class="js-author"></h3>
</div>
</template>
You have done almost everything right except you caught only first tag with class="kiddo".Looking at your question, as you need to update all the values inside tags which have class="kiddo" you need to catch all those tags which have class="kiddo" using document.getElementsByClassName("kiddo") and looping over the list while setting the innerHTML of each loop element to the userInput.
See this link for examples:https://www.w3schools.com/jsref/met_document_getelementsbyclassname.asp
try:
document.querySelectorAll('.kiddo')
with
<b class="kiddo">dude</b>

add text to div with javascript

Hello I'm just starting to learn and I'm trying to write simple code to add text to a div box using java script but it gives me error query selector not defined
html code:
<h2>List of items</h2>
<input class="text" type="text" placeholder="write text"><br>
<input type="button" value="Add" onclick="addItem()">
<div class="list"></div>
java script code:
function addItem(){
let getText = querySelector("text").value;
let newText = document.createElement("div");
newText.innerHTML = document.appendChild("getText");
document.querySelector("list").appendChild("newText");
}
There are several issues in your code:
querySelector is a method of document object. It should be document.querySelector("selector").
document.appendChild expects a Node instance. You are passing a string.
You are missing . for the class selectors.
You should not wrap variables with "" when you are referring to them.
Here is the updated code:
function addItem() {
let getText = document.querySelector("input.text").value;
let newText = document.createElement("div");
newText.innerHTML = getText;
document.querySelector(".list").appendChild(newText);
}
use
document.querySelector("div.list").appendChild("newText");
instead of
document.querySelector("list").appendChild("newText");

jQuery/Javascript - Get value of text input field, and display in div

I am testing getting a text input, and printing the result in a div below. However, I can't see to get it to work.
If the "placeholder" of the input field to a "value", it inexplicably works. I may just be tired, and missing something obvious, but I can't for the life of me work out what's wrong.
//Tested and didn't work
//var URL = document.getElementById("download")[0].value;
//var URL = document.getElementsByName("download")[0].value;
var URL = $('#download').val();
function downloadURL() {
//Print to div
document.getElementById("output").innerHTML = URL;
//Test, just in case innerHTML wasn't working
alert(URL);
}
<p><input type="text" name="download" id="download" placeholder="Download URL"></p>
<button onclick="downloadURL()">Test</button>
<div id="output"></div>
Just a small change, you have to get value when you click on button, so first save a reference to that field and then get value when required
var URL = $('#download');
function downloadURL(){
//Print to div
document.getElementById("output").innerHTML = URL.val();
// alert(URL.val());
}
If you want to go jQuery...
var URL = $('#download');
function downloadURL() {
$("#output").html(URL.val());
}
... or plain JavaScript
var URL = document.getElementById("download") ;
function downloadURL() {
document.getElementById("output").innerHTML = URL.value;
}
I'd recommend you to stick with jQuery. Let jQuery behave in an unobtrusive way instead of relying on an inline event handler attached to the button.
<p> <input type="text" name="download" id="download" placeholder="Download URL"></p>
<button>Test</button> //remove the inline click handler
<div id="output"></div>
$('button').on('click', function() {
var url = $('#download').val();
$('#output').text(url); //or append(), or html(). See the documentation for further information
});
Minor modifications on your code so that it can be aligned to "Unobtrusive Javascript".
HTML
<p>
<input type="text" name="download" id="download" placeholder="Download URL">
</p>
<button id="btnDownloadUrl">Test</button>
<div id="output"></div>
jQuery
$(function(){
$("#btnDownloadUrl").bind("click", function(){
var downloadUrl = $("#download").val();
$("#output").html(downloadUrl);
});
});

Replace multiple <br>'s with only one <br>

How do I use JavaScript to detect
<br>
<br>
<br>
to become one
<br>
?
I tried with:
jQuery('body').html().replace(/(\<br\>\r\n){3, }/g,"\n");
but this is not working for me.
CSS Solution
If you want to disable the effect of multiple <br> on the page, you can do it by CSS without using JavaScript:
br + br { display: none; }
Check the jsFiddle demo.
However, this method is ideal when you are working with tags, something like this:
<div>Text</div><br /><br /><br />
<div>Text</div><br /><br /><br />
<div>Text</div><br /><br /><br />
In other cases, like this:
Hello World<br /> <br />
Hello World<br /> <br />
Hello World<br /> <br />
It will fail (as CSS passes text nodes). Instead, use a JavaScript solution.
JavaScript Solution
// It's better to wait for document ready instead of window.onload().
window.onload = function () {
// Get all `br` tags, defined needed variables
var br = document.getElementsByTagName('br'),
l = br.length,
i = 0,
nextelem, elemname, include;
// Loop through tags
for (i; i < l - 1; i++) {
// This flag indentify we should hide the next element or not
include = false;
// Getting next element
nextelem = br[i].nextSibling;
// Getting element name
elemname = nextelem.nodeName.toLowerCase();
// If element name is `br`, set the flag as true.
if (elemname == 'br') {
include = true;
}
// If element name is `#text`, we face text node
else if (elemname == '#text') {
// If text node is only white space, we must pass it.
// This is because of something like this: `<br /> <br />`
if (! nextelem.data.replace(/\s+/g, '').length) {
nextelem = br[i+1];
include = true;
}
}
// If the element is flagged as true, hide it
if (include) {
nextelem.style.display = 'none';
}
}
};
Check the jsFiddle demo.
What is the point of sending HTML, which is in a form that you don't want, to the client browser and making it run JavaScript code to clean it up? This looks like a bad design.
How about fixing all your static HTML, and HTML generation, so that these superfluous <br> elements do not occur in the first place?
If you use JavaScript to modify the document object, do so for dynamic effects that cannot be achieved in any other way.
Simpler:
var newText = oldText.replace(/(<br\s*\/?>){3,}/gi, '<br>');
This will allow optional tag terminator (/>) and also spaces before tag end (e.g. <br /> or <br >).
Wouldn't something like this be the right approach:
$("br~br").remove()
EDIT: No, it's wrong, because its definition of "contiguous" is too loose, as per BoltClock.
This solution is jQuery + DOM only, does not manipulate HTML as string, works with text nodes, ignores whitespace only text nodes:
$('br').each(function () {
const {nodeName} = this;
let node = this;
while (node = node.previousSibling) {
if (node.nodeType !== Node.TEXT_NODE || node.nodeValue.trim() !== '') {
break;
};
}
if (node && node !== this && node.nodeName === nodeName) {
$(node).remove();
}
});
See: https://jsfiddle.net/kov35jct/
Try this
$('body').html($('body').html().replace(/(<br>)+/g,"<br>"));
It will replace n number of <br> into one.
Demo
I would go with this:
$('body').html($('body').html().replace(/<br\W?\\?>(\W?(<br\W?\\?>)+)+/g,"<br>"));
However, after reading the comments in another post here I do consider that you should try to avoid doing this in case you can correct it in the back end.
A lot of the other answers to this question will only replace up to certain amount of elements, or use complex loops. I came up with a simple regex that can be used to replace any number of <br> tags with a single tag. This works with multiple instances of multiple tags in a string.
/(<br>*)+/g
To implement this in JavaScript, you can use the String.replace method:
myString.replace(/(<br>*)+/g, "<br/>");
To replace multiple <br/> tags, add a / to the regex:
/(<br\/>*)+/g
Try this:
jQuery('body').html(
jQuery('body').html().replace(/(?:<br>\s+){3,}/ig,"\n"));
);
DEMO:
jsfiddle

javascript in html

i am using javascript to change the text of div tag on run time.
how can this be done..
my div tag is as:
<div id="topdiv" style="color:Blue" onmouseover="button1();">
<input type="button" id="btndiv" onclick="edit1();"/>
Div Tag
</div>
i wnt the user to input text on runtime in div and that should be displayed in div.
can someone help me..
It should be innerHTML. innerHTM is not a javascript function.
You don't get a magic variable just by having an element with an id. var something = document.getElementById('some-id')
The property is called innerHTML not innerHTM
innerHTML is a string variable not an function. Assign a value to it with =, don't try to call it with ()
function edit1() {
alert('you are in edit1');
document.getElementById('topdiv').innerHTML = 'hello';
}
and with proper error handling:
function edit1() {
alert('you are in edit1');
var topDiv = document.getElementById('topdiv');
if (topDiv != null) {
topDiv.innerHTML = 'hello';
} else {
alert('topdiv is nowhere to be found in this DOM');
}
}
Try document.getElementById('topdiv').innerHTML = "Hello"
To get the div you should use document.getElementById('topdiv'). There is indeed a WebKit feature, that elements with an ID are automatically expanded as global variables, but it's highly questionable, that this becomes mainstream.
Then, innerHTM should read innerHTML, and you assign directly:
foo.innerHTML = "hi there"
you should use
document.getElementById('topdiv').innerHTML = 'hello';
You should use references instead of ID's, using this.
In that case this means the node that triggers the event.
<div style="color:Blue" onmouseover="button1(this);">
<input type="button" onclick="edit1(this);"/>
Div Tag
</div>
function button1(divRef){
//divRef is the reference to the DIV
}
function edit1(inputRef){
//inputRef is the reference of the INPUT
//inputRef.parentNode is the reference to the DIV
}
function edit1() {
alert('you are in edit1');
document.getElementById('topdiv').innerHTML = 'hello';
}
This should work by specifying the id
In standard JavaScript usage you'd do as per #DarinDimitrov 's answer.
document.getElementById("topdiv").innerHTML = ('hello');
Once you're happy with JavaScript I would suggest you look at the JQuery libraries - the powerful syntax will let you write short, neat code like this:
$("#topdiv").html('hello');
Your file
<div id="topdiv" style="color:Blue" onmouseover="button1();"> Div Tag</div>
<form><input type="button" id="btndiv" value="Edit" onClick="window.open('t2.html','popuppage','width=850,toolbar=1,resizable=1,scrollbars=yes,height=700,top=100,left=100');" value="Open popup"/></form>
t2.html file
function sendValue (s){var selvalue = s.value;window.opener.document.getElementById('topdiv').innerHTML = selvalue;window.close();}
<form name="selectform"><input name="details" value=""><input type=button value="Copy input to parent opener" onClick="sendValue(this.form.details);"></form>
Got Idea from this source enter link description here

Categories

Resources