I currently take baby steps in JS development and coded the following link adder:
const button = document.getElementById('button')
const listdiv = document.querySelector('.listdiv')
button.addEventListener('click', function(){
let input = document.getElementById('text').value
let createA = document.createElement('a')
createA.setAttribute('href', input)
let linkDescr = document.createTextNode(input)
createA.appendChild(linkDescr)
listdiv.appendChild(createA)
})
The order of instruction is this:
Get the value of the text box
Create <a>
Set <a>'s link description
Set href
add <a>'s description to <a>
And then add all of <a> to the pre-existing Div..
So far so good. But, why is it that when we set href, it gets automatically added to <a>, but we have to take an extra step to add the link's description? Isn't let linkDescr = document.createTextNode(input) supposed to add the description automatically as well? My theory is that the commands are different in that we directly set an attribute of <a> for one, but create a variable on the other; and something need's to be done first with this variable. Variables don't just do anything by themselves. Please educate me on my logic. Also feel free to propose code changes/suggestions/flaws.
Thank you
There are often multiple ways to do things.
For example, the href can be added like this:
createA.href = input;
So then the description can also be added as a property.
createA.textContent = input;
The API simply gives us the choice. Appending a text node may make more sense in some cases, like when you're relocating an existing node.
In your case, you're creating a new text node. This is an object that is independent of any other part of the DOM tree, so it doesn't do anything until you insert it in the position where you want it, like inside the new a element.
Related
I'm not really familiar with Javascript, and even less with how Javascript works in Chrome's F12 developer tools. What I'm trying to do is have a favorite which, when clicked on, loads a web page but removes some of the clutter of the page which is loaded (I don't really care if it removes it before the page is loaded, or loads it and then removes it)
For now, I'm trying to figure out how to remove all elements except the one I want to keep (and its' children), namely, one which has the following html:
<div>
<ul class="c-list-news u-relative" data-load-more-content>...</ul>
</div>
I'm trying the following (from what I could find on SO), but I can't find the right selector (or I'm doing something else wrong, not quite sure):
var elem = document.querySelectorAll('body *:not(div ul.c-list-news, div ul.c-list-news *)');
for(var i=0;i<elem.length;i++) {
elem[i].parentElement.removeChild(elem[i]);
}
(PS : I haven't yet looked into how to put it into a favorite/extension, it will come later)
It's probably easier than you realize. :-) You can get the first element matching .c-list-news like this:
const cListNews = document.querySelector(".c-list-news");
If you want to keep its parent, just add .parentNode to that:
const divContainer = document.querySelector(".c-list-news").parentNode;
Then, wipe out body entirely:
document.body.innerHTML = "";
...and put the element back:
document.body.appendChild(cListNews); // Or `divContainer`
I'm not sure I'd expect the page to continue to be readable, though, since of course this completely changes where the element is in the DOM, which may well make the CSS fail.
You can't make a bookmark (favorite) that both loads the page and does this in one go, because javascript: bookmarks work within the context of the current page. You could use something like TamperMonkey which is an extension that lets you run a script automatically when you go to matching URLs.
But you can make a bookmark that you use when you're already on the page: Just use the javascript: pseudo-protocol and follow it with JavaScript code. For instance:
javascript:var divContainer %3D document.querySelector(".c-list-news").parentNode%3Bdocument.body.innerHTML %3D ""%3Bdocument.body.appendChild(divContainer)%3Bconsole.log("done")%3B
I created that by simply removing line breaks from the code (optional), running the code through encodeURIComponent, and putting javascript: on the front. (Some folks would also convert spaces to %20.)
Save the element to keep to a variable. Remove all nodes from the body, or the element that you want, and add the element to keep. Example:
let elementToKeep = document.getElementById('side');
const myNode = document.getElementsByTagName("body")[0];
while (myNode.firstChild) {
myNode.removeChild(myNode.firstChild);
}
myNode.appendChild(elementToKeep);
Using the removeChild method is faster that setting the innerHtml as empty string.
Check here: Remove all child elements of a DOM node in JavaScript
I want do to click and display in textarea.
The problem is once I click the fullname, the fullname will display in textarea;
and then click ic, the ic will display in textarea but replaced the fullname.
What should I do to make fullname,ic,hp not replace each other? I want to let user click by the variable they want, therefore I didnt do 3 variables insert in one click.
<span onclick=\"insert_user_eh_name('".$row['fullname']."','','');\">".$row['fullname']."</span>
<span onclick=\"insert_user_eh_name('','".$row['ic']."','');\">".$row['ic']."</span>
<span onclick=\"insert_user_eh_name('','','".$row['hp']."');\">".$row['hp']."</span>
function insert_user_eh_name(fullname,ic,phone){
jQuery("#text-area").val(fullname+ ic +phone);}
So, if you're using jQuery, here's the solution you would want:
var insertIntoTextArea = null;
$('.data').on('click', function(){
insertIntoTextArea += $(this).text();
$("#text-area").val(insertIntoTextArea);
});
Now, you can create the identifier any way you would like, but I used a class just to make it easier. One thing to remember is it's not usually a good idea to mix JS and PHP together. It just ends up being a mess and you'll run into so many problems. Also, it's not how jQuery is meant to operate.
That said, what I did was create a click event handler that will know that on click, append it to the textarea's value and make sure it is ADDED to the existing data, rather than overwrite what they previously had in the textarea.
Does this help?
Here's a JSfiddle just in case
embeded JS code you write in HTML is really strange, but if you don't want the string to replace each other in val, why not add them? for example:
// fullname click
var val = $('#text-area').val()
$('text-area').val(val + fullname)
All you need to write is about string process
say for instance i have the following line:
var arrowBase = document.createElement('div')
Now within this div tag i want to add some HTML (i.e text).
Then i tried the following:
arrowBase.innerHTML('hello');
However this does nothing:S
i have also tried: arrowBase.HTML('hello');
But once again without any result
I know is that rather simple but in my search i could'nt find the answer hope someone is able to help me out here
Read the docs, it is not a method.
arrowBase.innerHTML = 'hello';
arrowBase.textContent = "HELLO"
also does the same thing but only text can be specified. Whereas in innerHTML html tags can be specified along with the text.
Im trying to write a small js script that will let a user input a string of text and then output it wrapped in some html to the page.
I know how to do this with php, but it seems a little bit of an overkill for such a simple action, plus im always keen to learn something new.
I was playing around using document.myform.submit(); but i wasnt sure how to submit the form value to a variable and then output that var to the screen using document.write();
Any ideas how i would do this ?
Ive created a jsfiddle of the problem here - http://jsfiddle.net/pudle/axcLz/
There are many ways to do it. Here is the code that shows one of them:
document.getElementById("myform").onsubmit = function (event) {
var link = document.getElementById("mylink");
var textField = document.getElementById("text");
link.href = textField.value;
textNode = document.createTextNode(textField.value);
if (link.hasChildNodes()) {
link.removeChild(link.lastChild);
}
link.appendChild(textNode);
event.preventDefault();
};
jsfiddle: http://jsfiddle.net/TMJGH/5/
I added an id attribute to the a element to make things easier.
First line says that we want to change the function that handles "onsubmit" event in our form and then we define that function. The "event" argument is used only to call .preventDefault() in the last line which basically means that we don't want the form to be actually submitted.
We need to get access to DOM elements in the javascript code, so I used document.getElementById. Then I set the href attribute to the value of the textField. To change the actual link text I created a new text node with the value of the textField (it is possible to use textNode.innerHTML but that won't escape HTML code if someone inserts it in the text field). Then I check if our a element already has some text in it - if yes, it has to be removed. Finally I append the text element as a new child to our a element.
If you want to append more HTML nodes inside a node you can easily create them with document.createElement('element name') and append them to link. I also have to mention that jQuery makes playing with DOM a lot easier.
I feel like this is a simple question, but I am still relatively new to javascript and jquery.
I am developing a site for a touch interface that uses unordered lists and jquery .click functions to take input data. I have a section to input a m:ss time, with 3 divs, each containing a list of digits for time. I need to get the input for each column and set it as a variable. I originally designed the inputs to change form inputs, because I didn't understand javascript very much. It was easy to change the 3 hidden inputs by using div id's, but I can't figure out how to do it now with javascript variables.
Here is my original jquery code...
$("div#time>div>ul>li").click(function() {
var id = $(this).parents(".time").attr("name");
var number = $(this).html();
$("input#"+id).val(number); });
The last line sets one of 3 hidden inputs equal to whatever was clicked. I need to make it so separate variables take the inputs, then I can manipulate those variables however I want.
Here's a short snippet of the html, to have an idea of how jquery grabs it.
<div id="time">
<h1>Time</h1>
<div name="minute" class="time" id="t_minute">
M :
<ul>
The full time html is here: link text
Thanks everyone!
I've been using SO to answer many questions I've had, but I couldn't find something for this, so I figured I would join, since I'm sure I will have more questions along the way.
So I have tried adding the following, and I still can't get it to work right.
window.myValues[id] = number;
event[i].min = myValues["minute"];
event[i].sec = myValues["second"];
event[i].sin = myValues["single"];
event[i].time = String(event[i].min) + String(event[i].sec) + String(event[i].sin);
I tried it both with and without the quotation marks. I have not used window.* for anything, so I'm not very sure how to handle this.
First thing to mention here, don't be unnecessary specific. In your example
$('#time').find('li').click()
should be enough.
If I understand you well, you want to store the some data. You might want to use
jQuery's $.data method. Example:
$('#time').find('li').click(function(){
var $this = $(this);
var name = $this.closest('.time').attr('name');
$.data(document.body, name, $this.html());
});
This would store the html of the clicked li in a global Object, which can be accessed like
alert($.data(document.body, 'minute'));
you should be able to reference the variable from the window[] object, so something like window[id] should do the trick for referencing the variable.