Creating a variable for the text node of each element - javascript

I am trying to create a variable for each element in a set. I have an HTML structure like this:
<div id="notes">
<p>Example Text 1</p>
<p>Example Text 2</p>
<p>Example Text 3</p>
</div>
I want to store the text of each of the elements in a separate variable. In this case the elements are dynamically generated, so sometimes there are 2 elements, sometimes there are more.
What I have tried so far:
var $counter= 0;
var variableNote = {};
$('#notes p').each(function(){
$counter += 1;
variableNote["newNote"+$counter] = $("#notes p").text();
console.log(newNote1);
});
What I am doing wrong?

Object properties are not variables. To access them you need to refer to the object.
Also, you're not using the current element of the iteration in your loop.
var variableNote = {};
$('#notes p').each(function(index) {
variableNote["newNote" + (index+1)] = $(this).text();
});
console.log(variableNote["newNote1"]);

This can be achieved by finding the elements and reducing them into a single object.
//lookup the p tags, and reduce them to a single object
var variableNotes = $('#notes p').get().reduce(function(notes, note, index){
notes['newNote'+ ++index] = note.innerText;
return notes;
}, {});
console.log(variableNotes);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="notes">
<p>Example Text 1</p>
<p>Example Text 2</p>
<p>Example Text 3</p>
</div>

var variableNote = {};
$('#notes p').each(
(i,e) => variableNote["newNote" +(i+1)] = $(e).text()
);
console.log( variableNote );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="notes">
<p>Example Text 1</p>
<p>Example Text 2</p>
<p>Example Text 3</p>
</div>

It can be done using vanilla javascript
var variableNotes = [...document.querySelectorAll("#notes p")].reduce((noteList, note, i)=>{
noteList['newNote'+ (i +1)] = note.innerText;
return noteList;
}, {});
console.log(variableNotes);
<div id="notes">
<p>Example Text 1</p>
<p>Example Text 2</p>
<p>Example Text 3</p>
</div>

Related

How to get the value of several paragraphs with the class name using Javascript?

I want to get the text of the paragraph (p) contained in div by clicking on that div using the class name. I tried using innerText and innerHTML but it returns undefined in the console. How can I do it using only Javascript?
HTML
<div class="showName">
<p class="paragraphs">Text 1</p>
</div>
<div class="showName">
<p class="paragraphs">Text 2</p>
</div>
<div class="showName">
<p class="paragraphs">Text 3</p>
</div>
Javascript
const showName = document.getElementsByClassName('showName');
const paragraphs = document.getElementsByClassName('paragraphs');
Array.prototype.forEach.call(showName, function(element) {
element.addEventListener('click', function() {
// How can I do it here?
});
});
Working example: https://codepen.io/shinaBR2/pen/qBbxRgz
Basic code is
Array.prototype.forEach.call(showName, function(element) {
element.addEventListener('click', function() {
// How can I do it here?
const text = element.querySelector('.paragraphs').textContent;
alert(text);
});
});
If you want to get text inside all the paragraphs having "paragraphs" class, this code can also help you:
HTML
<div class="showName">
<p class="paragraphs">Text 1</p>
</div>
<div class="showName">
<p class="paragraphs">Text 2</p>
</div>
<div class="showName">
<p class="paragraphs">Text 3</p>
</div>
JAVASCRIPT
const showName = document.getElementsByClassName('showName');
const paragraphs = document.getElementsByClassName('paragraphs');
for(i=0; i < paragraphs.length; i++){
console.log(paragraphs[i].innerText);
}

Changing html element's position in parent tag when created it with document.createElement

I'm just starting learning Javascript, and right now I'm on document.createElement. I understood that you can create a HTML tag this way, and that afterwards you have to put it into a HTML tag that already exists (parent). My question is Can I choose exactly where I put this created HTML tag in the parent tag ?
Let's say for exemple I have the following HTML :
<div id="parent">
<div>
<p>First paragraph</p>
</div>
<p>Second paragraph</p>
<p>Third paragraph</p>
</div>
And this javascript :
const getMyDiv = document.getElementById("parent");
const createParagraph = document.createElement("p");
getMyDiv.appendChild(createParagraph);
I will have the following result :
<div id="parent">
<div>
<p>First paragraph</p>
</div>
<p>Second paragraph</p>
<p>Third paragraph</p>
<p></p>
</div>
So what i'm asking is how can I create this <p> at a different position, for exemple like this :
<div id="parent">
<div>
<p>First paragraph</p>
</div>
<p>Second paragraph</p>
<p></p>
<p>Third paragraph</p>
</div>
.appendChild(), indeed append your created element at the end of the list of the children of your selected element, as you demonstrated.
Though, there are other methods that can be used, based on your needs, so you can mount your element wherever you want e.g. .insertBefore() or .prepend()
There are some differences on how they work, so I suggest you take a look on the provided links so you can understand the differences.
You can use this script if you want to place the position to a specific location
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<style>
</style>
<script language="javascript">
function myFunction(){
//var getMyDiv = document.getElementById("parent");
//var createParagraph = document.createElement("p");
//getMyDiv.appendChild(createParagraph);
var child = document.createElement('p')
var parent = document.getElementById("parent");
parent.insertChildAtIndex(child, 2)
}
Element.prototype.insertChildAtIndex = function(child, index) {
if (!index) index = 0
if (index >= this.children.length) {
this.appendChild(child)
} else {
this.insertBefore(child, this.children[index])
}
}
</script>
<button onclick="myFunction()">Try it</button>
<div id="parent" style="background-color:red;width=100px;height:100px">
<div>
<p>First paragraph</p>
</div>
<p>Second paragraph</p>
<p>Third paragraph</p>
</div>
to check save as html file and look at the inspection element in the browser

How to get each value of same class name?

I have some tag with same class , i want get each their value and append it to a div how to do it
<p class="adr">location1</p>
<p class="adr">location2</p>
<p class="adr">location3</p>
<p class="adr">location4</p>
for (i=1;i<$(".adr").length;i++) {
$("#test").append($(".adr").html() + "</br>");
}
the result :
location1
location1
location1
location1
it seems did apppend 4 times first class, how to get 1 and 2 and 3 and 4 ?
Use each in jquery to get text of all adr class . Do not append line by line as it takes more execution time.Try to append as a whole, Hope this helps
var str=''
$('.adr').each(function(e){
str+=$(this).text()+ "<br>"
})
$("#test").html(str)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p class="adr">location1</p>
<p class="adr">location2</p>
<p class="adr">location3</p>
<p class="adr">location4</p>
<div id =test></div>
$('#test').append($('.adr').clone());
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p class="adr">location1</p>
<p class="adr">location2</p>
<p class="adr">location3</p>
<p class="adr">location4</p>
<div id="test"></div>
You can append all matched elements with .adr using append(). But only this would technically add the original elements and strip from it where it was previously situated in the DOM. So, clone() them to create a new copy of all elements and preserve it's previous state as well.
var rows = $(".adr");
for (var i = 0; i < rows.length; i++) {
$("#test").append($(rows[i]).html() + "<br>")
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p class="adr">location1</p>
<p class="adr">location2</p>
<p class="adr">location3</p>
<p class="adr">location4</p>
<div id =test></div>
$('.something') returns an array, so you need $('.something')[i] to get each item from the array.
You're calling three jQuery functions for every iteration of the loop - inefficient. Call them once each before the loop, assigning them to a variable, then use the variable instead of the jQuery calls.
You can use each() method. Secondly selecting "#test" and ".adr" is a bad idea declare them as global variable and use them.
let elms = $(".adr");
let test = $('#test');
elms.each(function(){
test.append($(this).html() + "<br>")
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p class="adr">location1</p>
<p class="adr">location2</p>
<p class="adr">location3</p>
<p class="adr">location4</p>
<div id="test">
</div>
Using querySelectorAll() and map()
document.querySelector('#test').innerHTML = [...document.querySelectorAll('.adr')].map(x => x.innerHTML).join("<br>")
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p class="adr">location1</p>
<p class="adr">location2</p>
<p class="adr">location3</p>
<p class="adr">location4</p>
<div id="test">
</div>

Get text of specific element by ID using $(this) keyword

I have several boxes and inside each of the boxes I have different title and headline elements.
I would like to know how I can get the text of the desired element inside the corresponding box that has been clicked, not all of the text elements.
Here's what I'm working with:
box.onclick = function(){
alert($(this).text());
};
This displays all of the text elements data in the alert box. I would like to solely target a single specified text element that has an id to get the text from it instead.
Any help would be appreciated.
You can use find() to target the child element:
$('.box').on('click', function() {
console.log($(this).find('h3').text())
})
.box{
background: #adadad;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='boxes'>
<div class='box'>
<h3>title 1</h3>
<h4>subtitle 1</h4>
</div>
<div class='box'>
<h3>title 2</h3>
<h4>subtitle 2</h4>
</div>
<div class='box'>
<h3>title 3</h3>
<h4>subtitle 3</h4>
</div>
</div>
HTML
<div id = "content">
<div id = "box">
<p>This is the box content 1 </p>
</div>
<div id = "box">
<p>This is the box content 2</p>
</div>
</div>
JS
$('*[id*=box]:visible').each(function(index) {
$(this).click(function() {
alert($(this).text());
});
});
Test it here:
https://codepen.io/bmvr/pen/WMZPXW

Group Selected Elements: document.querySelectorAll

Hi how can I group my document.querySelectorAll if I have a case like this:
<div>
<p class="flower">Flower 1</p>
<p class="bee">Bee 1</p>
<p class="tree"></p>
</div>
<div>
<p class="flower">Flower 2</p>
<p class="dude"></p>
<p class="snow-leopard"></p>
</div>
<div>
<p class="flower">Flower 3</p>
<p class="tree"></p>
<p class="mountain"></p>
<p class="wizard"></p>
<p class="bee">Bee 3</p>
</div>
I always want to select the flower, if there is a bee I want to have it attached to the flower, I don't care about the rest. The flowers and bees don't have a specific order in the div and there are cases with no bee. Also assume that there is a class at the flower and bee but the rest of the structure isn't as clean as in the example. The only solution I have so far is to go a few levels up and then use regex. At the end I want to include them both into a json:
[{flower: "yellow", bee:"bumblebee"},...]
This approach:
var flowers = document.querySelectorAll(flower);
var bees = document.querySelectorAll(bee);
And then iterating afterwards over the both arrays does not work.
The problem is that you can't really match the flowers with the bees simply with CSS selectors. You need to iterate over all flowers and find the bee sibling if there is one. One way to do this is to get the parent of a flower and then look for bees.
var obj = Array.prototype.map.call(document.querySelectorAll(".flower"), function(f){
var node = {flower: f.textContent};
var bee = f.parentNode.querySelector(".bee");
if (bee) {
node.bee = bee.textContent;
}
return node;
});

Categories

Resources