How to get each value of same class name? - javascript

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>

Related

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

Creating a variable for the text node of each element

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>

jquery - select an element with specific content

I have an html structure like this:
<div class="test">
<span class="content">1</span>
</div>
<div class="test">
<span class="content">2</span>
</div>
...
<div class="test">
<span class="content">100</span>
</div>
In my javascript code, I need to get an <span> element with class content that has exactly 1 or 2 , ..., 100
I tested jquery .contains method, but this returns all elements that have for example 1. such as 1, 12, ....
You can use filter method which accepts a callback function applied to every item.
var array=$('.test').find('.content').filter(function(){
return $(this).text().trim()==100;
});
console.log(Array.from(array));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="test">
<span class="content">1</span>
</div>
<div class="test">
<span class="content">2</span>
</div>
<div class="test">
<span class="content">100</span>
</div>
You can proceed in the following manner:
$('.content').each(function(){
if($(this).html() == "2")
{
console.log("THE SPAN WITH 2 IS ");
console.log($(this)[0]);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="test">
<span class="content">1</span>
</div>
<div class="test">
<span class="content">2</span>
</div>
<div class="test">
<span class="content">100</span>
</div>
What we do here is check through the content class of the spans and check if their inner html is 2 and if it is we console.log it.
You can use the vanilla .indexOf() method.
The indexOf method takes a parameter of the string you want to find and returns either the index (if it's found), or -1 if it's not.
var myEl = document.querySelector(".test"):
for loop...
if( myEl.innerHTML.indexOf(2) != -1 ){
console.log("This element contains the number 2")
}
You can use .filter(), get and check .textContent or .innerHTML of element, at .filter() callback you can use RegExp N$ where N is number to match. For example, to match elements having "1" or "2" set at .textContent you can use RegExp /1$|2$/; to match "100", /100$/; with RegExp.prototype.test()
var filtered = $("span.content").filter((_, {textContent}) =>
/1$|2$/.test(textContent));
filtered.css("color", "green");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
<div class="test">
<span class="content">1</span>
</div>
<div class="test">
<span class="content">2</span>
</div>
...
<div class="test">
<span class="content">100</span>
</div>
You can do something like this..
$('.test').each(function() {
if($(this).text == '1')
{
var a = $(this).html();
}
});
a will now contain the html of that span which contains your text.

Check for number of html element then run a function

I have three different scenario where the span element presents.
No child span element:
<div class="text" contenteditable="true" id="example">
<div class="outside">Type here</div>
</div>
One child span element:
<div class="text" contenteditable="true" id="example">
<div class="outside">Type here <span class="inside"> please.</span></div>
</div>
Multiple child span element with same class name
<div class="text" contenteditable="true" id="example">
<div class="outside">Type here<span class="inside"> please </span> thanks</div>
<div class="outside">Name <span class="inside"> please.</span> thanks.</div>
</div>
I want to run the following function:
var len = $('span.inside').get(0).nextSibling.length;
console.log(len);
Because the span class can be present once or multiple times, or not at all, I want to check for the presence of the span. Then based on the number of times the span element is there, I would need to run the function for all the span element.
How would I achieve this?
var length = $('span.inside').length;
if (length > 0) {
$('span.inside').each(function() {
var len = $(this).get(0).nextSibling.length;
console.log(len);
})
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="text" contenteditable="true" id="example">
<div class="outside">Type here<span class="inside"> please </span> thanks</div>
<div class="outside">Name <span class="inside"> please.</span> thanks.</div>
</div>
Use class and get length.
For many span use .each() to iterate over
I want to check for the presence of the span.
You can achieve this by checking the length property of the selector:
var $spans = $('span.inside');
var numberOfSpans = $spans.length;
Based on the number of times the span element is there, I would need to run the function for all the span element
This is a simple if statement, then you can use each() to loop over the elements in a selector:
if (numberOfSpans > 5) { // 5 just an example
$spans.each(function() {
// do something with the span here...
});
}

jQuery Insert closing div tag and opeing div tag after count

I am trying to get jquery to close a div and inset an opening div with a class after x amount of items.
Here is what I have tried:
$(this).after('</div> <div class=\"bar">Bar');
it outputs:
<div class="bar">Bar</div>
What I need is:
<div class="item2">
<div class="CountThese2"> Count Me </div>
<div class="CountThese2"> Count Me </div>
</div>
<div class="bar">
<div class="CountThese2"> Count Me </div>
<div class="CountThese2"> Count Me </div>
</div>
<div class="bar">
<div class="CountThese2"> Count Me </div>
<div class="CountThese2"> Count Me </div>
</div>
<div class="bar">
<div class="CountThese2"> Count Me </div>
<div class="CountThese2"> Count Me </div>
</div>
http://jsfiddle.net/yoderman94/JEtj2/
You can't add half a tag. I think what you're trying to do is wrap the elements. Your fiddle is pretty messy, but here's a simple example of how you can do that:
http://jsfiddle.net/9Q62H/
while($('#wrapper > a:lt(2)').wrapAll('<div class="bar">bar</div>').length) { }
Which turns this:
<div id="wrapper">
1
1
1
1
1
1
1
1
</div>
into this:
<div id="wrapper">
<div class="bar">bar
1
1
</div>
<div class="bar">bar
1
1
</div>
<div class="bar">bar
1
1
</div>
<div class="bar">bar
1
1
</div>
</div>
You can't manipulate the DOM that way, with or without jQuery. To accomplish the same thing, insert a new div after the current div's parent, and then move all of the current div's following siblings to the new div:
var bar = $("<div>").addClass("bar").text("Bar");
bar.insertAfter($(this).parent());
bar.append($(this).nextAll());
Edit: To preserve text nodes, including the whitespace between your links, it's not quite as simple as $(this).nextAll(), sadly. You need to use .contents() to select the text nodes, then slice at the index of this:
var contents = $(this).parent().contents();
var bar = $("<div>").addClass("bar").text("Bar");
bar.insertAfter($(this).parent());
bar.append(contents.slice(contents.index(this) + 1));
http://jsfiddle.net/JEtj2/6/
I'm going to recommend a different approach here. When you call .after() you need to be giving it a complete open and close tag. You cannot open a tag then close it later like you are trying to above.
My advice would be to try and take an approach like the following, so you can pass a complete open and close tag to .after()
var theDiv = "<div class='bar'>";
for(var i = 0; i < 2; i++) {
theDiv += '<div class="CountThese2"> Count Me </div>';
}
theDiv += "</div>";
$('#thing').after(theDiv);
See how I constructed the whole div including contents before calling .after() ?

Categories

Resources