I have this HTML:
<div id = "options"></div>
I access to this div trough this Javascript:
var test = "hola";
document.getElementById('options').innerHTML=
<p>Test</p> <li>${test}</li>
And I have this button:
function click({
document.getElementById("Click").addEventListener("click", function(){
});
};
click();
I need that when that function called "click" is executed automatically that <li> can clean that value of the variable: "test" and it is seen empty.
How can I do it? Thank you
el.innerHTML is the property which keeps track of HTML text values shown inside the element. You can set that to empty whenever you want to clear it.
Try this sample - https://jsitor.com/J0gXikZmV
<div id = "options"></div>
var test = "hola";
let el = document.getElementById("options");
el.innerHTML = "<p>Test</p> <li>${test}</li>";
el.addEventListener('click', () => {
el.innerHTML = '';
})
Here it clear the html content of div
Related
I'm studding HTML, CSS and JS and while I was creating an exercise, I was forced to stop due to an error. I created an button dynamically, setted an onclick to it and then created a function with that onclick. The problem is that the function isn't working, at leats it doesn't made anything till now.
let formularys = document.querySelector('section#formulary')
let slct = document.createElement('select')
let opts = document.createElement('option')
let optp = document.createElement('option')
let fbtn = document.querySelector('input#formularybtn')
let nbtn = document.createElement('input')
let br = document.createElement('br')
slct.id = 'pors'
slct.size = '2'
opts.value = 'rsite'
opts.innerHTML = 'Rate site'
optp.value = 'rp'
optp.innerHTML = 'Rate products'
nbtn.setAttribute('type', 'button')
nbtn.setAttribute('value', 'Next')
nbtn.setAttribute('onclick', 'nbutton')
function nbutton(){
console.log('Next working')
/*if(slct.selectedIndex == 1){
console.log('Valid rate choose')
}*/`enter code here`
}
instead of using setAttribute you can just do
nbtn.onclick = nbutton
in javascript, onclick isn't a string but a function.
The problem is, you are not appending your html code generated from JavaScript to DOM. You can either append to main DOM like below
document.body.appendChild(nbtn);
document.body.appendChild(optp);
or you can append them to some parent div by first getting div id
document.getElementById("divId").appendChild(nbtn);
where divId is id of your div where you want to add this html.
Also you should assign event listener in correct way as suggested by Tony and Rashed Rahat.
Try:
element.onclick = function() { alert('onclick requested'); };
First, sorry I'm not good with javascript.
HTML:
<div id="Comment-ID">
<p class="comment-content">...</p>
</div>
The javascript: (Edit: Added the whole code)
<script type='text/javascript'>
function autoloadmore() {
var loadmoreClass = document.getElementsByClassName("loadmore")[0];
var loadmoreChild = loadmoreClass.querySelector('a')
if (loadmoreClass) {
loadmoreChild.click();
}
}
//<![CDATA[
function InsertarImagenVideo(id) {
var IDelemento = document.getElementById(id),
sustituir = IDelemento.innerHTML;
sustituir = sustituir.replace(/\[img\](.[^\]]*)\[\/img\]/ig, "<img class='img-comentarios' src='$1'\/>");
document.getElementById(id).innerHTML = sustituir;
}
//]]>
window.onload = function() {
autoloadmore();
setTimeout(function(){
InsertarImagenVideo('Comment-ID');
},3000);
};
</script>
"InsertarImagenVideo" replaces some text inside with an image. Instead of using it on "Comment-ID", I want to use it on "Comment-class".
Note: I can't edit the HTML.
I couldn't find anything when I searched, or maybe I didn't know how to look. Can someone help me with this?
You can use document.querySelector to select an element by class:
Update this line:
var IDelemento = document.getElementById(id),
to var IDelemento = document.querySelector(id),
and pass the class selector to your method InsertarImagenVideo
setTimeout(function(){
InsertarImagenVideo('.comment-content');
},3000);
I found a simple way to insert an image into the <p class="comment-content">...</p> element by grabbing the parent <div id="Comment-ID">.
I'm assuming that you need to grab the unique id to then access the inner <p> element to replace the existing text with an image. This code grabs the unique id element, then grabs the first <p> tag using .getElementsByTagName('p')[0]. One thing I did add is a proper image load script to update the <p> tag with the image once it has been loaded (maybe this removes the need for that setTimeout function you have?).
let classElement = document.getElementById("Comment-ID").getElementsByTagName('p')[0];
let imageObject = new Image();
imageObject.src = `https://www.clipartmax.com/png/full/1-14442_smiley-face-png-smiley-png.png`;
imageObject.onload = function() {
classElement.innerHTML = `<img id="myImg" src="${imageObject.src}" />`;
let imageElement = document.getElementById(`myImg`);
imageElement.width = 100;
imageElement.height = 100;
};
Here's a JSFiddle demo of the upper code in action.
Hope this helps :)
Here's the code...
https://jsfiddle.net/6n2k65zs/
Try add a new item, you'll see its not working for some reason but it should be...
I can't spot any errors in the code, can someone help me out please?
And does anyone know any good debuggers? debugging JS is a nightmare!
Thanks.
<!DOCTYPE html>
<html>
<head>
<title>JavaScript To-Do List</title>
<link href="css/style.css" rel="stylesheet">
</head>
<body>
<input id="input" type="text">
<button id="btn">Add</button>
<hr>
<ul id="todo">
</ul>
<ul id="done">
</ul>
<!-- javascript anonymous self-invoking function -->
<!-- Function expressions will execute automatically -->
<script>
// from outside the action you wont be able to access the variables
// prevents another variable with a same name from conflicting
(function(){
var input = document.getElementById('input');
var btn = document.getElementById('btn');
// Object for the lists
// the reason im using ID is because ID can only be named once rather than a class which can be named 100's of times
var lists = {
todo:document.getElementById('todo'),
done:document.getElementById('done')
};
/* Parameter is string
create a list element which is stored in 'el' and returns it
*/
var makeTaskHtml = function(str, onCheck) {
var el = document.createElement('li');
var checkbox = document.createElement('input');
var label = document.createElement('span');
label.textContent = str;
checkbox.type = 'checkbox';
checkbox.addEventListener('click', onCheck);
// el.textContent = str;
// can use this method to move an element from one element to another
el.appendChild(checkbox);
el.appendChild(label);
// Text content is grabbing the text from the text box and storing it in variable el.
return el;
};
var addTask = function(task) {
lists.todo.appendChild(task);
};
var onCheck = function(event){
var task = event.target.parentElement; //targets the item clicked
var list = task.parentElement.id;
//lists.done.appendChild(task);
//swaps the 2 objects around
lists[list === 'done' ? 'todo' : 'done'].appendChild(task);
this.checked = false;
input.focus();
};
var onInput = function() {
var str = input.value.trim; // trim removes white space...
if (str.length > 0) {
addTask(makeTaskHtml(str, onCheck));
input.value = '';
input.focus();
}
};
btn.addEventListener('click', onInput);
input.addEventListener('keyup', function(event){
var code = event.keyCode;
console.log(code);
if (code === 13) {
onInput();
}
});
input.focus();
addTask(lists.todo, makeTaskHtml('Test done', onCheck));
}());
</script>
</body>
</html>
It appears to me you are not calling trim as a method, but accessing it as a variable?
Try add the () in trim:
var onInput = function() {
var str = input.value.trim(); // trim removes white space...
Your addTask function is being called with 3 parameters:
addTask(lists.todo, makeTaskHtml('Test done', onCheck));
but the function definition for addTask only takes one parameter:
var addTask = function(task)
so you need to just call addTask with just makeTaskHtml parameter, and not lists.todo which is already referenced inside the addTask function or onCheck
Or for debugging in Chrome, try Cmd-Alt–I in (Mac) or Ctrl-Alt-I (Windows).
First of all, you shouldn't put your scripts inline in JSFiddle – put them in the JS box to protect everyone's sanity! It's what it's made for...
There are other issues in the code, but the main issue seems to be in this line:
var str = input.value.trim;
Here, you're assigning str to the JS function trim. You want to assign it the the results of trim(), so try:
var str = input.value.trim();
You're still getting other errors in the console, but the basics seem to work.
code :
<script src="Scripts/jquery-1.8.2.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
var $this = $("#Test_txtarea");
var txtval = $this.val();
$this.find("img").each(function () {
var imgbytes = $(this).attr("name"); // extract bytes from selected img src
$(this).replaceWith(imgbytes);
});
$("#NewVal").html(txtval);
});
</script>
html
<textarea ID="Test_txtarea" >Hi <img src='test.png' name='test' > kifak <img src='test2.png' name='test1' > Mnih <img src='test3.png' name='test3' ></textarea>
<span id="NewVal" ></span>
what i am trying to do is basically trying to replace each img tag by it's name so the final textarea value will be like this : Hi test kifak test1 Mnih test3
this is the jsfiddle : http://jsfiddle.net/Ga7bJ/2/
the .find("img") always return 0 as length.how can i fix this code ?
Though it is not complete answer or at least not going to be "Copy paste" answer, there is few things you need to do here:
The content of Textarea is VAL of it and not InnerHTML. So, you have to pick that content as value and than create a hidden div and put it as HTML. Once you did it, you can now find the HTML tags in it using find rather easily.
Once you find tag you can find the name using attr() function
Once you have name, than you again go back to val() of textarea, and do regex replace or using HTML you can replace as well I guess, but not sure.
Look at this jsFiddle. What is does is:
It gets the value from your Test_txtarea and sets that as the html of a hidden div.
The hidden div wil render the images within the textarea.
After they have been rendered, I find these images,
- get the source,
- remove all characters after the .
- replace the entire html of the image with the src.
After all that has been done you are left with a div with the value you wanted.
All what is done next is the html from the div is copied to the value of your textarea.
function replaceImageWithSrc(value){
var div = $("#invisible");
div.html(value);
var images = div.find("img");
images.each(function(index){
var src = $(this).attr("src").split(".")[0];
this.outerHTML = src;
});
return div.html();
}
$(document).ready(function () {
var txtArea = $("#Test_txtarea");
var txtval = txtArea.val();
txtval = replaceImageWithSrc(txtval);
txtArea.val(txtval);
});
The following code works for me. Basically, I get the value of the text area and append it to an off-screen div. Now that I have valid markup nesting, I can iterate the child-nodes as normal.
function byId(e){return document.getElementById(e)}
function newEl(t){return document.createElement(t)}
function test()
{
var div = newEl('div');
div.innerHTML = byId('Test_txtarea').value;
var msg = '';
var i, n = div.childNodes.length;
for (i=0; i<n; i++)
{
if (div.childNodes[i].nodeName == "IMG")
msg += div.childNodes[i].name;
else if (div.childNodes[i].nodeName == "#text")
msg += div.childNodes[i].data;
}
byId('NewVal').innerHTML = msg;
}
I have the following script
var counter = 0;
function appendText(){
var text = document.getElementById('usertext').value;
if ( document.getElementById('usertext').value ){
var div = document.createElement('div');
div.className = 'divex';
var li = document.createElement('li');
li.setAttribute('id', 'list');
div.appendChild(li);
var texty = document.createTextNode(text);
var bigdiv = document.getElementById('addedText');
var editbutton = document.createElement('BUTTON');
editbutton.setAttribute('id', 'button_click');
var buttontext = document.createTextNode('Edit');
editbutton.appendChild(buttontext);
bigdiv.appendChild(li).appendChild(texty);
bigdiv.appendChild(li).appendChild(editbutton);
document.getElementById('button_click').setAttribute('onClick', makeAreaEditable());
document.getElementById('usertext').value = "";
counter++;
}
};
var makeAreaEditable = function(){
alert('Hello world!');
};
I want the makeAreaeditable function to work when the Edit button is pressed(for each of the edit buttons that are appended under the textarea).. In this state, the script, alerts me when i hit the Addtext button.
the following is the html. P.S. i need this in pure javascript, if you can help. thanks
<textarea id="usertext"></textarea>
<button onClick="appendText()">Add text </button>
<div id="addedText" style="float:left">
</div>
instead of:
document.getElementById('button_click').setAttribute('onClick', makeAreaEditable());
you need to do this:
editbutton.onclick = makeAreaEditable;
the function's name goes without brackets unless you want to execute it
instead of obtaining the element from the DOM using document.getElementById('button_click')
you can use the editbutton variable already created. this object is the DOM element you are looking for
SIDE NOTE:
the standard way to do it is to add the onclick property before appending the element