Cannot get context element text - javascript

This is pretty straight forward but I caannit get the expected result. I want to iterate over a set of paragraph elements and get their text node using .each() function although I get the entire document text nodes.
Here is the code
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<main>
<p>Kon</p>
<p>Mule</p>
</main>
<p>Hello riko</p>
<h2 hidden data-modal-target=".modal-progress">Header 2</h2>
</body>
<script type="text/javascript">
$(function () {
// console.log($("p"))
$("p").each((index)=> {
console.log( $( this ).text())
// console.log(index)
})
})
</script>
</html>
Instead of getting:
Kon
Mule
Hello Riko
I get this:
Kon
Mule
Hello riko
Header 2
$(function () {
// console.log($("p"))
$("p").each((index)=> {
console.log( $( this ).text() + index)
// console.log(index)
})
})
three times.
Where am I wrong?

this is not accessible in arrow functions. You need to use regular functions to do that:
$("p").each(function(index) {
console.log($(this).text())
// console.log(index)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<main>
<p>Kon</p>
<p>Mule</p>
</main>
<p>Hello riko</p>
<h2 hidden data-modal-target=".modal-progress">Header 2</h2>
Or you need to get the native JS array from the jQuery collection using get() and use forEach() on it:
$("p").get().forEach((item) => {
console.log($(item).text())
})

You are doing everything correct as per code. Something is wrong with your environment. here is working code
https://jsfiddle.net/RanjeetKumarGautam/w6ojokp1/
$(function () {
// console.log($("p"))
$("p").each((index)=> {
console.log( $( this ).text())
// console.log(index)
})
})

Related

How can I use a parameter to change HTML text?

I'm using an API, and am trying to access the value of product.shoeName to change text on my HTML page. This is my code:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript"
src="shoepoo.js">
</script>
</head>
<body>
<div>
<p id="text" style="color:purple;
font-weight:bold;font-size:20px;">
</p>
<script type="text/javascript"> shoeName(); </script>
</div>
</body>
</html>
const SneaksAPI = require('sneaks-api');
const sneaks = new SneaksAPI();
//getProducts(keyword, limit, callback) takes in a keyword and limit and returns a product array
function shoeName(){
sneaks.getProducts("Jumbo Blazer", 1, function(err, products){
products.forEach(
function names (product) {
document.getElementById("text").innerHTML = product.shoeName;
})
});
};
Basically, I want product.shoeName to be shown as text, but nothing is showing up. How can I fix this? I understand it's a local function which is probably stopping the data from being shown (or something like that), but how can I work around this?
Made below changes in shoepoo.js
products.forEach((product)=> {
document.getElementById("text").innerHTML = product.shoeName;
});
But you need to create dynamic HTML components if there is multiple data in products. Otherwise, it set the last shoeName in the paragraph component.

Replacing a div with the content of another html-file ('common/...html) with VanillaJS instead of jQuery

I would like to be able to write the following without having to import a jQuery Library in order to get the div replaced by content of a component written in another html-file:
<head>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<script>
$.get("common/navbar.html", function(data) {
$("#navbar-placeholder").replaceWith(data);
});
</script>
<div id="navbar-placeholder"></div>
</body>
Would be happy for suggestions
You can do like below, you might have to change per your requirement.
fetch('common/navbar.html')
.then(response => {
var el = document.getElementById('navbar-placeholder');
el.insertAdjacentHTML('afterbegin', response);
})
Here response needs to be HTML.
https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
https://developer.mozilla.org/en-US/docs/Web/API/Element/insertAdjacentHTML
I tried it with fetch like suggested by Gowtham Raj J but it didn't work right away. But with a second .then chained after the first response it runs well:
fetch('common/navbar.html')
.then(res => {
return res.text();
})
.then(cont => {
var navPlaceholder = document.getElementById('navbar-placeholder');
navPlaceholder.insertAdjacentHTML('afterbegin', cont);
});

the string str is always empty although it is filled with data from the.geojson file any idea?

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function() {
$("#p1").load("reporting/data.geojson").toString();
var str = document.getElementById("p1").innerHTML;
document.getElementById("p2").innerHTML = str;
});
</script>
</head>
<body>
<div id="div1">
<h2>try</h2>
</div>
<p id="p1"></p>
<p id="p2"></p>
</body>
</html>
this is the code, p1 clearly shows on the screen but my actual problem is that i cant fill the string with it, "maybe the load function is the last to act i dont know" kinda new on this. I need to put the .geojson text in a string, or any other way to extract the coordinates would save me the trouble of string eddting. thank you iij advance
You need to use the callback of load to get the data from #p1.
The load method is asynchronous, so the code does not wait for the data to load and executes the next statement.
$(document).ready(function() {
$("#p1").load("reporting/data.geojson", function() {
var str = document.getElementById("p1").innerHTML;
document.getElementById("p2").innerHTML = str;
});
});
As you're using jQuery, you can use html()
$(document).ready(function () {
$("#p1").load("reporting/data.geojson", function () {
$('#p2').html($('#p1').html());
});
});

How do I pass this JSON data to an autocomplete

Special thanks to Raúl Monge for posting a fully working code for me.
My problem was getting JSON data from a file.json and using this data to autocomplete search on it with JavaScript. The code that finaly got it working for me is the following:
<script>
$(document).ready(function(){
var arrayAutocomplete = new Array();
$.getJSON('json/telefoonnummers.json', function(json) {
$.each(json.personen.persoon,function(index, value){
arrayAutocomplete[index] = new Array();
arrayAutocomplete[index]['label'] = value.naam+" - "+value.telefoonnummer;
});
$( "#search" ).autocomplete({source: arrayAutocomplete});
});
});
This is the html:
<body>
<div id="content">
<input type="text" id="search" />
</div>
And this has to be included in the head:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css"/>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
Thanks stackoverflow!
NEW EDIT CODE WORKING:
<script>
$(document).ready(function(){
var arrayAutocomplete = new Array();
$.getJSON('data.json', function(json) {
$.each(json.persons.person,function(index, value){
arrayAutocomplete[index] = new Array();
arrayAutocomplete[index]['label'] = value.name;
arrayAutocomplete[index]['value'] = value.phoneno;
});
$( "#search" ).autocomplete({source: arrayAutocomplete});
});
});
</script>
Add this in head
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css"/>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
This is the html
<body>
<div id="content">
<input type="text" id="search" />
</div>
</body>
why not use
var data = [
"Aragorn",
"Arwen",
....
];
since all of those data are labels?
There you go
A working example with the data structure you have.
Just initialize the autocomplete once the JSON is loaded & the data is formatted.
$( "#search" ).autocomplete({source: availableTags});
Your document ready is within your function.
Try to write your function outside of your document ready.
Then write your document ready to call your function.
Some something like this:
function loadJson() {
//alert("Whoohoo, you called the loadJson function!"); //uncomment for testing
var mycontainer = [];
$.getJSON( "data.json" , function(data) {
//alert(data) //uncomment for testing
$.each( data, function( key, val ) {
//alert("key: "+key+" | val: "+val); //uncomment for testing
array.push([key , val]);
});
});
return mycontainer;
}
$(document).ready(function(){
//alert("Boojah! jQuery library loaded!"); //uncomment for testing
var content = loadJson();
dosomethingwitharray(content);
});
Hope this helps!
Also make sure you have jQuery included in your head ( <head> </head> ):
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
And add your javascript at the end of your body ( <body> </body> ).
To test if jquery does it's job try this:
<html>
<head>
<title>getting started with jquery</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
</head>
<body>
<h1>my page</h1>
<p>this paragraph contains some text.</p>
<!-- javascript at end -->
<script>
$(document).ready(function(){
//show a dialog, confirming when the document is loaded and jquery is used.
alert("boojah, jquery called the document ready function");
//do something with jquery, for example, modify the dom
$("p").append('<br /> i am able to modify the dom with the help of jquery and added this line, i am awesome.');
});
</script>
</body>
</html>
PS. Uncomment alerts for testing stuff, so you can test what happens. If you have space in your document i suggest using $.append to an div that log's all action's so you can see exactly what's going on because alert's in a loop like the .each are quite annoying! more about append: http://api.jquery.com/append/

Obtain this.index(this) in jQuery plugin

How can I clicked on that I get a tag index
My Html Code
<html>
<head>
<title>nss plugin</title>
<link rel="stylesheet" type="text/css" href="style.css">
<script type="text/javascript" src="../js/jquery.js"></script>
<script type="text/javascript" src="nss.js"></script>
<script type="text/javascript" src="script.js"></script>
</head>
<body>
<img src="../img/is1.jpg"/>
<img src="../img/is2.jpg"/>
<img src="../img/is3.jpg"/>
<img src="../img/is4.jpg"/>
</body>
</html>
2 . My jquery plugin code.
(function( $ ) {
$.fn.nss = function( ) {
var thisindx = this.index(this);
console.log(thisindx);
return this;
};
}( jQuery ))
3.my javascript code
$(function(){
$('a[rel="group"]').click(function(){
$('a[rel="group"]').nss();
})
});
Why thisindx value is equal to 0
How can a person get the actual value
Not sure why you need a plugin, you can just do :
$(function(){
$('a[rel="group"]').on('click', function(){
$('a[rel="group"]').index(this);
});
});
to get the current elements index withing the group.
EDIT:
inside a plugin you get the collection, and iterate over it with return this.each, so using each individual iteration and the collection, you can get the elements index in the set of elements in the selector like so:
$.fn.nss = function( ) {
var elems = this
return elems.each(function() {
// all plugin code for multiple elements should normally go in a loop
// like this one to perform the same actions on every element
var thisindx = elems.index(this);
console.log(thisindx);
});
};
Try like this
var thisindx = this.index();
Or from the click event you can directly get the index value like
$(function(){
$('a[rel="group"]').on('click',function(){
$('a[rel="group"]').index();
//Better use like
$(this).index(); //or this.index();
});
});

Categories