how to get text from child element from console - javascript

I'm trying to get the which is in
as you can see:
<p class="jmbadge">
<strong>xxx</strong>
<br>
<span class="field-value">text!</span>
</p>
I'm trying to get the <span>
this is inside a website and I want to take the text of <span> via the console (Google Chrome)
here is what I tried:
const jminfo = document.getElementsByClassName("jminfo");
const span = jminfo.querySelector('span');
console.log(span);
And here is the error I get:
Uncaught TypeError: jminfo.querySelector is not a function
at <anonymous>:1:21

const jminfo = document.getElementsByClassName("jmbadge")[0];
const span = jminfo.querySelector('span');
console.log(span);
<p class="jmbadge">
<strong>xxx</strong>
<br>
<span class="field-value">text!</span>
</p>

That is because you selected a punch of elements with a class name but didn’t specify wich elements from these elements list.
Try to use:
const span = document.querySelector('.jminfo > span');
console.log(span);
but in case you know the index of the element in the document you can use:
const jminfo = document.getElementsByClassName("jmbadge")[N];
// n = the index
const span = jminfo.querySelector('span');
console.log(span);

Related

Switch Content of two Textareas using JavaScript

I have two textareas and I like to switch the content of these, so content of the first textarea shall be the content of the second textarea and vice versa. Following code just copy the content of the first textarea into the second, but the second step is not performed, so both textareas comprise the same content afterwards. No error occurs.
function switch_text_content(){
var src_text_memory = src_form.src_message.value;
var trgt_text_memory = trgt_form.trgt_message.value;
console.log(src_text_memory);
src_form.src_message.innerHTML = trgt_text_memory;
trgt_form.trgt_message.innerHTML = src_text_memory;
//switch_text_content2(trgt_text_memory);
}
You are doing in wrong way because you are using .innerHTML to set value instead you can to use .value property to set value of textarea. Like Below Example:
const switchBtn = document.querySelector('#switch-btn');
const firstTextarea = document.querySelector('#first-textarea');
const secondTextarea = document.querySelector('#second-textarea');
switchBtn.addEventListener('click', function() {
const firstContent = firstTextarea.value;
const secondContent = secondTextarea.value;
firstTextarea.value = secondContent;
secondTextarea.value = firstContent;
});
<textarea id="first-textarea">First Content</textarea>
<textarea id="second-textarea">Second Content</textarea>
<br/>
<button type="button" id="switch-btn">Switch</button>

How to add break tags after inserting a paragraph into html using javascript's createElement

I've successfully inserted a paragraph element into html page using javascript but the 2nd consecutive paragraph comes side by side and I wish to add a break tag to print them in another line, how do I do that?
Here is a screenshot of my output:
Here is my javascript code:
function newtask(){
let ask = prompt("Enter the description of task");
const para = document.createElement("p");
const Textnode = document.createTextNode(ask);
para.appendChild(Textnode);
let text= document.getElementById("new")
text.appendChild(Textnode);
}
Here is the relevant html
<script src="index.js"></script>
<h1>To do List</h1>
<button onclick="newtask()">New Task</button>
<div id="new">
<p>test</p>
</div>
You were appending Textnode to your parent element, not your new <p> element. Here's a quick rewrite that should give you your desired results.
Firstly, create the new <p> element, then modify its innerText property. After that, just append your new <p>.
function newtask() {
const text = document.getElementById("new");
const ask = prompt("Enter the description of task");
const para = document.createElement("p");
para.innerText = ask;
text.appendChild(para);
}
You can wrap your p inside a div and add a display: flex configuration.
const paraDiv = document.createElement("div");
// Add your style configuration to your paraDiv
function newtask(){
let ask = prompt("Enter the description of task");
const para = document.createElement("p");
paraDiv.appendChild(para)
const Textnode = document.createTextNode(ask);
para.appendChild(Textnode);
let text= document.getElementById("new")
text.appendChild(Textnode);
}

Saving values to localStorage() and making them stay when I reload the page in Javascript

I am currently making a note writing app and need your help.
I'm struggling to understand how localStorage() works and how exactly I saved things to it. I would like to reload the page and have every note that I've written not dissappear.
Thank you.
//// Declare Variables ////
const noteBtn = document.querySelector('.add-note-btn');
const writeNote = document.querySelector('.note-input');
const allSavedNotes = document.querySelector('.added-notes');
//// Write new note and add to list ////
noteBtn.addEventListener('click', function(e){
// Create new paragraph element
let newNote = document.createElement('p');
// Add clas name to element
newNote.className = 'saved-note';
// Add the text input
newNote.textContent = writeNote.value;
// Append element to div
allSavedNotes.appendChild(newNote);
e.preventDefault();
})
<div class="all">
<div>
<div class="title">
<h1 class="heading">Notes List</h1>
</div>
<div>
<div class="writing-notes">
<textarea class="note-input" cols="35" rows="10"></textarea>
Add note
</div>
<div class="added-notes">
</div>
</div>
</div>
</div>
You can save all notes in localStorage by appending the state to an empty array.
I've intitally created a state variable that contains earlier undefined or an empty array.
Then appendNotes function appends a paragraph to the allSavedNotes DOM selector.
//// Declare Variables ////
const noteBtn = document.querySelector('.add-note-btn');
const writeNote = document.querySelector('.note-input');
const allSavedNotes = document.querySelector('.added-notes');
const state = JSON.parse(localStorage.getItem('notes')) || [];
function appendNotes(text) {
let p = document.createElement('p');
p.textContent = text;
// Append element to div
allSavedNotes.appendChild(p);
}
// append notes on page load
state.map(s => appendNotes(s));
//// Write new note and add to list ////
noteBtn.addEventListener('click', function(e) {
// Create new paragraph element
let newNote = document.createElement('p');
// Add class name to element
newNote.className = 'saved-note';
const text = writeNote.value.trim();
// Add the text input
newNote.textContent = text;
// if there are no `notes` in `localStorage` then use empty array
if (text !== "") {
state.push(text)
localStorage.setItem('notes', JSON.stringify(state));
}
// Append element to div
appendNotes(text);
newNote.textContent = "";
e.preventDefault();
})
<div class="all">
<div>
<div class="title">
<h1 class="heading">Notes List</h1>
</div>
<div>
<div class="writing-notes">
<textarea class="note-input" cols="35" rows="10"></textarea>
Add note
</div>
<div class="added-notes">
</div>
</div>
</div>
</div>
The above code won't from StackOverflow directly as it gives a cross-origin error:
Uncaught SecurityError: Failed to read the 'localStorage' property from 'Window': The document is sandboxed and lacks the 'allow-same-origin' flag.
But it works on JSFiddle. Here's a working link → https://jsfiddle.net/deadcoder0904/036bp9zy/33/
You can learn more about localStorage in this excellent blog post → https://www.digitalocean.com/community/tutorials/js-introduction-localstorage-sessionstorage

Adding content into an element in html using javascript

I want to create a paragraph element and add content to it. Basically i want to let the textContent of a paragraph element be a string.
What i have tried doing is:
var st="Hello";
con=document.getElementById("content");
var pv=document.createElement("p");
con.appendchild(pv);
pv.setAttribute("",st);
<span id="content"> </span>
What attribute should i use to add in the setAttribute function here? I tried using textContent but it's not an attribute. Any other way i can do this?
You could do with elem.innerText instead of setAttribute
var st = "Hello";
var con = document.getElementById("content");
var pv = document.createElement("p");
con.appendChild(pv);
pv.innerText= st;
<span id="content"> </span>
You should use innerText to do this.
pv.innerText = "hello"
You can set and get the text value of an element using innerText.
More info on innerText can be found here:
https://www.w3schools.com/jsref/prop_node_innertext.asp
You can also use innerHTML which can change not just the text but also the HTML.
let con_txt = document.getElementById("content_text");
let pv_txt = document.createElement("p");
con_txt.appendChild(pv_txt);
pv_txt.innerText = "From innerText";
let con_html = document.getElementById("content_html");
let pv_html = document.createElement("p");
con_html.appendChild(pv_html);
pv_html.innerHTML = "<b>innerHTML also works!</b>"; //You can use HTML tags here
<span id="content_text"></span>
<span id="content_html"></span>
Above result in HTML
<span id="content_text">
<p>From innerText</p>
</span>
<span id="content_html">
<p><b>innerHTML also works!</b></p>
</span>
More info about innerHTML

For loop not working as expected with string replacement

I am trying to make a javascript webextension that adds a couple of numbers eg. "123" to the end of the inner text of a hyperlink text to each product on a shopping website, eg. http://www.tomleemusic.ca
For example, if I go to this link, http://tomleemusic.ca/catalogsearch/result/?cat=0&q=piano
I want to add the item's identification number to the end of the product's name.
name of product and the href tag are in its item link, tomleemusic.ca/xxxxxx with the x's being the item number
However with my following code, I simply append the item number of the first item in the list to every item, instead of a different item number for each item.
var productsListLink = document.querySelectorAll(".products-grid .item .product-name a:not(.product-image)");
for (var i = 0; i < productsListLink.length; i++) {
var a = productsListLink[i];
var name = a.innerHTML || "";
var addon = document.querySelector(".products-grid .item .product-name a:not(.product-image)").getAttribute('href');
var newaddon = addon.replace("http://tomleemusic.ca/","");
name += newaddon;
a.innerHTML = name;
a.setAttribute('title', name);
}
In this line, you're grabbing only the first matching element:
var addon = document.querySelector(".products-grid .item .product-name a:not(.product-image)").getAttribute('href')
You already have the element you're actually working with in each loop iteration in a; just use that instead:
var addon = a.getAttribute('href')
Example:
var productsListLink = document.querySelectorAll(".products-grid .item .product-name a:not(.product-image)");
for (var i = 0; i < productsListLink.length; i++) {
var a = productsListLink[i];
var name = a.innerHTML || "";
var addon = a.getAttribute('href');
var newaddon = addon.replace("http://tomleemusic.ca/","");
name += newaddon;
a.innerHTML = name;
a.setAttribute('title', name);
}
<div class="products-grid">
<div class="item">
<span class="product-name">
</span>
</div>
<div class="item">
<span class="product-name">
</span>
</div>
<div class="item">
<span class="product-name">
</span>
</div>
</div>
querySelector will always return the first matching element. Thus, when you do
var addon = document.querySelector(".products-grid .item .product-name a:not(.product-image)").getAttribute('href');
you're selecting the first a (the one you get in your first iteration).
But, you can make the code a whole lot cleaner by using array methods and a regular expression to match the id:
Array.prototype.forEach.call(
document.querySelectorAll(".products-grid .item .product-name a:not(.product-image)"),
(productNameElement) => {
const idMatch = productNameElement.href.match(/\d+$/);
if (idMatch) productNameElement.appendChild(document.createTextNode(idMatch[0]));
});
Also note that only some of the elements have an ID number. For example, one of the search results:
BENCHWORLD SONATA 1c Single Adjustable Artist <span class="searchindex-highlight">Piano</span> Bench In Polished Walnut
doesn't have one, so it would be good to check that there's a match first.

Categories