Strings not setting in JS - javascript

I am working on a javascript project, and I am having trouble displaying an appended string. Right now, I am trying to change Crawler1 and Crawler2 to username that a user input. These usernames are stored in local storage:
<div id="wrap">
<div id="left_col">
<p id="p1">Crawler 1</p>
</div>
<div id="right_col">
<p id="p2">Crawler 2</p>
</div>
</div>
This is the JS script I am using in order to change the p1 and p2 values to the user names. I am very confused why nothing is appending, because when I use a window.alert box,
localStorage.getItem("name") and localStorage.getItem("name2") print the expected values.
document.forms["game"]["p1"].innerHTML = localStorage.getItem("name");
document.forms["game"]["p2"].innerHTML = localStorage.getItem("name2");
does anyone have any idea why the p1 and p2 values wouldn't be changing?

did you try using...
document.querySelector('#left_col p').innerHTML = localStorage.getItem("name");
document.querySelector('#right_col p').innerHTML = localStorage.getItem("name");
...?
Or if you really need to scope the query inside the form
const form = document.querySelector('form[name=game]');
form.querySelector('#left_col p').innerHTML = localStorage.getItem("name");
form.querySelector('#right_col p').innerHTML = localStorage.getItem("name");
[edit] Explanation
Looking your markup, you want to access to a <p> inside a <div id="">.
document.querySelector() allows you to get a DOMElement using a CSS selector.
The css selector #left_col p matches all the <p> inside an element with id="left_col".
More on CSS Selectors: https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors

Forms returns an HTMLCollection of HTMLFormElements
You can access the collection with the id of the names and this will return a HTMLFormElement. But using ['element-id'] on the HTMLFormElement won't do anything.
Instead you can use querySelector as #simnutoli has shown or getElementById like below.
localStorage.setItem('a', 'b');
document.getElementById("p2").innerHTML = localStorage.getItem('a');

Related

Insert Javascript variable value into HTML tag id field

I am trying to organize a bunch of id tags, I would like to be able to set up a single JavaScript variable which holds all manner of interesting information. One place I would like to use it, is to set the value of an id field in an HTML tag
<script>
var messageID = { idText: "message1", other: "qwerty"};
</script>
<div id="message0">Text Zero</div>
<div id="JavaScript.messageID.idText">Text One</div> <!-- abject failure -->
So basically I want the messageID.idText value to be the id value: id="message1". Obviously the example fails in the second div line. Is there a way to do this?
Edit:
Ok, I want to be able to use the value of messageID.idText elsewhere in the system, such as
var elementTag = document.getElementById(messageID.idText);
I use the id in many places, and the more there are, the better a chance of mis-typing something. This is not a small project :-)
So I am going with:
<?php
$msgOneId = "message1";
?>
<script>
var messageID = { idText: "<?=$msgOneId?>", other: "qwerty"};
</script>
<div id="message0">Text Zero</div>
<div id="<?=$msgOneId?>">Text One</div>
and then
var elementTag = document.getElementById(messageID.idText);
works

How can I store an existing html element and create it later?

I have a very simple html code here. I want to store the whole div test_area and then create it when I need it. For now, let's assume that I want to duplicate it and put the clone below the existing element, how can I do that? Here's what I tried to do which didn't work (specifically the innerHtml line):
<body>
<div class="test_area" id="test_area">
<h1>
This is a test
</h1>
</div>
</body>
<script>
let current_element = document.getElementById('test_area')
let clone = document.createElement('div')
clone.innerHTML = current_element
document.body.appendChild(clone)
</script>
In the end I want the final html version to look like this:
This is a test
This is a test
Depends what you want to do with the element. You can store it in a variable and then render somewhere or you could store it to localstore or send to server or what ever you like. Here is a simple example:
<div class="test_area" id="test_area">
<h1>
This is a test
</h1>
</div>
<div id="clonearea"></div>
const current_element = document.getElementById('test_area');
const clonearea = document.getElementById('clonearea');
const clone = current_element.cloneNode(true);
clonearea.appendChild(clone);
You can read more about cloning here: https://developer.mozilla.org/en-US/docs/Web/API/Node/cloneNode
And here is a codepen example: https://codepen.io/shnigi/pen/LYRQGOW
You can simply convert the old object in a JSON, and then parsing it and save it to a var.
let myObject = JSON.parse( JSON.stringify( myOldObject ) );
this way you can access myObject and display it whenever you want.
Take a look to this question :
What is the most efficient way to deep clone an object in JavaScript?
This is not cloning, but a way to create and append in one line:
document.getElementById("test_area").appendChild(Object.assign(document.createElement("h1"), {textContent: "This is a test"}))
<body>
<div class="test_area" id="test_area">
<h1>
This is a test
</h1>
</div>
</body>
To actually clone, use cloneNode
https://developer.mozilla.org/en-US/docs/Web/API/Node/cloneNode
let p = document.getElementById("test_area").children[0]
let p_prime = p.cloneNode(true)
document.getElementById("test_area").appendChild(p_prime)
<body>
<div class="test_area" id="test_area">
<h1>
This is a test
</h1>
</div>
</body>
Apparently the only thing i should have done to fix this problem is use the variable's innerHTML and append it on the body, like this. I had totally forgotten that current element is an object, not the html code itself.
const current_element = document.getElementById('test_area');
document.body.appendChild(current_element.innerHTML)

Javascript: How to print input to <div> selected by class?

Edit: Thanks for the helpful answers so far! I'm still struggling to print the input to the "right" div, though. What am I missing?
Next to the input field, there is an option to select either "left" or "right". Depending on the selection, the input is to be printed eiether left or right on the click of a button. This is what I have - but it only prints to the left, no matter the selection.
jQuery(document).ready(function(){
$('.button').click(function(){
$('.input').val();
if ($('select').val() == "left"){
$('div.left').html($('.input').val());
}
else {
$('div.right').html($('.input').val());
}
});
});
</script>
Sorry if this is very basic - I am completely new to JS and jQuery.
I'm trying to print input from a form into a div. This is part of the source HTML modify (it's for a university class):
<input type="text" class="input">
<div class="left">
</div>
<div class="right">
</div>
Basically, text is entered into the field, and I need to print this text either to the "left" or the "right" div when a button is clicked.
So far, I have only ever dealt with divs that had IDs, so I used
document.getElementById("divId").innerHTML = ($('.input').val());
But what do I do now when I don't have an ID? Unfortunately, changes to the HTML source are not an option.
Thanks in advance!
Just use normal selectors, like css and jQuery does.
https://api.jquery.com/category/selectors/
in your case:
$('div.left').html($('.input').val());
As you see there are many ways to do this. You can get elements by tag name, class, id...
But the most powerful way is to get it with querySelector
function save() {
var input = document.querySelector('input').value;
document.querySelector('div.left').innerHTML = input;
}
<input type="text" class="input">
<button onclick="save()">Save</button>
<div class="left"></div>
<div class="right"></div>
There are plenty of other ways to target HTML elements, but the one you're looking for in this case is getElementsByTagName(). Note that this returns a NodeList collection of elements, so you'll additionally need to specify the index that you wish to target (starting at 0). For example, if you want to target the second <div> element, you can use document.getElementsByTagName("div")[1].
This can be seen in the following example:
let input = document.getElementsByTagName("input")[0];
let button = document.getElementsByTagName("button")[0];
let div2 = document.getElementsByTagName("div")[1];
button.addEventListener("click", function(){
div2.innerHTML = input.value;
});
<input type="text">
<button>Output</button>
<br /><br />
<div>Output:</div>
<div></div>
Since you have unique class names for each element, document.getElementsByClassName can be used. This will return an array of elements containing the class. Since you only have one element with each class name, the first element of the returned array will be your target.
<input type="text" class="input">
<button onclick="save()">Save</button>
<div class="left"></div>
<div class="right"></div>
<script>
function save() {
var input = document.getElementsByClassName('input')[0].value;
document.getElementsByClassName('left')[0].innerHTML = input;
}
</script>
This is one of the many ways to do what you want:-
Write the following in console:
document.getElementsByTagName("div");
now you can see the total number of div elements used in your current document/page.
You can select one of your choice to work on by using "index number"(as in array index) for that particular div.
Lets say your div having class name = "right" is the 3rd one among the other div elements in your document.
This will be used to access that div element.
document.getElementsByTagName("right")[2].innerHTML = "whatever you want to write";

Select a specific element from HTML data in a variable

I have stored the results of $.get() into a variable called questionsdata. The data is basically a bunch of divs with unique ids. I wish to find just one div using an id. I can kind of understand that this wouldn't work but I don't know what would.
$(questionsdata).find("#593");
Example data in the variable:
<div id="591">Stuff</div>
<div id="592">Stuff</div>
<div id="593">Stuff</div>
<div id="594">Stuff</div>
You can parse HTML stored in a text variable with jquery quite easily - it doesn't need to be added to the DOM.
As #593 is at the top level, .find will not find as it searches children. Instead you could use .filter if it will always be at the top level, or wrap in another <div> - either at the source or via jquery:
var data = '<div id="591">Stuff1</div><div id="592">Stuff2</div><div id="593">Stuff3</div><div id="594">Stuff4</div>';
console.log($(data).find("#593").length)
// Use .filter
console.log($(data).filter("#593").text())
// Or wrap with a div
console.log($("<div>").html(data).find("#593").text())
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
var questionsdata = '<div id="x"><div id="a591">Stuff1</div><div id="b592">Stuff2</div><div id="c593">Stuff3</div><div id="d594">Stuff4</div></div>'
console.log($('#b592',questionsdata ).html())
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Your JavaScript
var data='<div id=591>Stuff</div>
<div id="592">Stuff</div>
<div id="593">Stuff</div>
<div id="594">Stuff</div>';
var $data = $(data).appendTo('#container");
var my_div=$("#container").find("#593");
Your HTML
< div id="container"></div>
Your CSS
#container{display:none;}

HTML Parsing using javaScript

I am trying to get parse HTML document.
this is the HTML:
<h1>
<span class="memName fn" itemprop="name">Ankur Arora</span>
<span class="display-none" itemprop="image">http://photos1.meetupstatic.com/photos/member/3/8/f/8/member_249974584.jpeg</span>
<span class="display-none" itemprop="url">http://www.meetup.com/Meetup-API-Testing/members/191523682/</span>
</h1>
I need to get the picture and the name.
I try this code:
var name = document.querySelector("memName fn").name;
Anyone can help me? I'm new in javaScript...
Thanks
To get the inner text, you can use the text() function, like this:
HTML:
<span class="memName fn">Ankur Arora</span>
Jquery:
var memName = $(".memName").text();
console.log(memName); // Via console log
alert(memName); // Alert it
It's easy with jQuery. Just include it in your page:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
Then use .text() or .html() to extract the content of the span-elements
var pictureLink = $("span[itemprop='image']").text();
//.html() also gets the html-elements inside
var name = $("span[itemprop='name']").html();
https://jsfiddle.net/bh9mebru/
You can also use innerHTML to get the text.
<span id="memId" class="memName fn">Ankur Arora</span>
document.getElementsByClassName('memName') - This will give the list of elements having the class 'memName'
To get the first element's inner text use document.getElementsByClassName('memName')[0].innerHTML
or access by id .
document.getElementById('memId').innerHTML

Categories