jQuery class selector and text adding - javascript

I have two files index.html and star.js.
My index file looks so:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<div class="foo">
<h2>First:</h2>
<p>3</p>
</div>
<div class="foo">
<h2>Second:</h2>
<p>5</p>
</div>
</body>
<script type="text/javascript" src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
<script src="star.js" charset="utf-8"></script>
</html>
And my js file looks like that:
var element = $(".foo > p");
//Try to figure it out
console.log('First: ' + element.text() + ' second: ' + element.text());
All I want from this code is just log out in the right sequence:
First: 3 second: 5
But my console gives me this:
First: 35 second: 35
I know that $(".%classname%) method looks thought all foo classes in the file but it doesn't return an array. Can I solve my problem somehow?
I need to use jQuery. Not pure js with .getElementsByClassName.
I can't change my classes name. .foo requires.
I need the solution which doesn't depend on number of classes.
The nearest solution I found in :eq() pseudo-selector but is there any other ways?

The text method will return text contents of all the elements present in the jQuery object.
You will have to iterate over the items in the elements then print each one like
var element = $(".foo");
element.each(function() {
var $this = $(this);
snippet.log($this.find('h2').text() + ': ' + $this.find('p').text());
})
<!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="foo">
<h2>First:</h2>
<p>3</p>
</div>
<div class="foo">
<h2>Second:</h2>
<p>5</p>
</div>

Try
$('.foo:nth-child(1) p').text()
and
$('.foo:nth-child(2) p').text()
EDIT: going to bring my answer out of fiddle for future reference:
Use a loop to iterate through any number of elements
for(i=1; i <= $('div.foo').length; i++){
$('.output').append($('.foo:nth-child('+i+') h1').text() + ": ");
$('.output').append($('.foo:nth-child('+i+') p').text() + "<br/>");
}

Related

Assigning a link and description to a column cards dynamically

I want to create column cards (like buttons).
in that cards, description should appear in its top and when it is clicked, separate link should be opened in new page.
every cards has its own description and link.it should not be hard coded by directly assigning the desc and link to it.and every function and elements should be assigned in javascript file not html.
the desc and link should given in an array like
Table={{"desc":"apple","link":"www.google.com"},{"desc":"banana","link":"www.youtube.com"}}
I tried this code and I'm getting only one card with last description and link
for(i=0;i<10;i++)
{
var temp=my.Table[i].link;
$('.demo').html('<div class="column"><p id="i"></p></div>');
document.getElementById(i).innerHTML ='' + my.Table[i].desc + '';
}
You can iterate the table object, after append what you should use.
HTML code:
<html>
<head>
<meta charset="UTF-8">
<script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous"></script>
<script src="script.js"></script>
<!-- <link rel="stylesheet" type="text/css" href="styles.css"> -->
</head>
<body>
<div class="demo">
</div>
</body>
</html>
And the jquery code looks like the following:
$(document).ready(function(){
const table=[{"desc":"apple","link":"www.google.com"},{"desc":"banana","link":"www.youtube.com"}];
table.forEach((v, i)=>{
$('.demo').append('<div class="column"><p id="temp_'+i+'">' + v.desc + '</p></div>');
});
});

Get specify parent element id using his class

I try get id parent p div (class mainRow), but my code in console return undefinied:
<div class="row mainRow" id="someId">
<div class="selected">
<p onclick="checkParentId(this)">Hello</p>
</div>
</div>
<script>
function checkParentId(element){
var a = $(element).parent( ".mainRow");
var b = $(a).attr("id");
console.log(b);
}
</script>
Link to jsfiddle: https://jsfiddle.net/50ev1jzq/
Since the .mainRow is not a parent of the paragraph, use .closest:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>parent demo</title>
<script src="https://code.jquery.com/jquery-3.5.0.js"></script>
</head>
<body>
<div class="row mainRow" id="someId">
<div class="selected">
<p onclick="checkParentId(this)">Hello</p>
</div>
</div>
<script>
function checkParentId(element){
debugger
var a = $(element).closest( ".mainRow" );
var b = $(a).attr("id");
console.log(b);
}
</script>
</body>
</html>
You could use parents(), because according to the docs:
Given a jQuery object that represents a set of DOM elements, the parent() method traverses to the immediate parent of each of these elements in the DOM tree and constructs a new jQuery object from the matching elements.
This method is similar to .parents(), except .parent() only travels a single level up the DOM tree.
As others have pointed out, closest() could also work. There are some differences tough:
I find sollution, i change .parent to .closest and code work
<div class="row mainRow" id="someId">
<div class="selected">
<p onclick="checkParentId(this)">Hello</p>
</div>
</div>
<script>
function checkParentId(element){
var a = $(element).closest( ".mainRow");
var b = $(a).attr("id");
console.log(b);
}
</script>

How to get a specific child divs value from parent using jquery

I know this question is so familiar in stackoverflow, but still I can't find my solution. I want to get my child div's value when I click the parent div, but my current code gives me "undefined". My html is given below:
<div class="main">
<div class="testId">
1
</div>
<div class="testName">
test
</div>
<div class="testDob">
10/10/10
</div>
</div>
and my script is given below
var id = $(this).child(".testId").innerHTML;
any thoughts?
Try using find():
var id = $(this).find(".testId").text();
"find" finds the elements just inside the div.main
var id = $(this).find(".testId").html();
console.log(id);
Use .children() no selector .child()
var id = $(this).children(".testId")[0].innerHTML;
or
var id = $(this).children(".testId").text();
or
var id = $(this).children(".testId").eq(0).text();
I think this one should works
$('.main').click(function(){
var value = $(this).child(".testId").text();
})
here is a working exmaple
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title></title>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
</head>
<body>
<div class="main">
<div class="testId">
1
</div>
<div class="testName">
test
</div>
<div class="testDob">
10/10/10
</div>
</div>
<script>
$(".main").click(function () {
var id = $(this).children(".testId").html();
alert(id)
})
</script>
</body>
</html>

How to share jQuery .data() data through iframe's?

I'm trying to share jQuery data from one or more iframe'd html pages with their parent html document.
What I need is an inter-iframe communication and if possible (highly desireble) to share/exchange .data() i.e. the $.cache of both jQuery objects (in the parent and child iframe).
Someting similar to this:
Parent html:
<!DOCTYPE html>
<html>
<head>
<title >iframe-data</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js" ></script>
<script type="text/javascript" >
jQuery(function($){
var testData = 'hello world from #div1';
$('#div1').data('test',testData);
var newTestData = $('.div2').closest('.div1').data('test');
$('#div2').append( 'Parent window: "' + testData + '" === "' + newTestData + '" => ' + (testData === newTestData) );
}); // jQuery()
</script>
</head>
<body>
<div id="div1" class="div1" >
<div id="div2" class="div2" >
</div>
<iframe src="iframe-data2.html" ></iframe>
</div>
</body>
</html>
Iframe html:
<!DOCTYPE html>
<html>
<head>
<title >iframe-data2</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js" ></script>
<script type="text/javascript" >
jQuery(function($){
var testData = 'hello world from #div1';
var $body = $(window.top.document.body);
var $div1 = $body.find('#div1');
var outsideTestData = $body.find('#div1').data('test');
var $div2 = $('#div2');
$div2.append( 'outside test data: "' + testData + '" === "' + outsideTestData + '" => ' + (testData === outsideTestData) );
}); // jQuery()
</script>
</head>
<body style="background-color: silver">
<div id="div1" class="div1" >
<div id="div2" class="div2" >
</div>
</div>
</body>
</html>
jQuery object itself is created inside anonymous function and it uses closure for accessing global (global for other jQuery functions) array inside this functions. So, as result: jQuery in iframe and jQuery in the top window have different data array. If you need top level data, use window.top.jQuery('#div1').data('test1') (please note that default context for jQuery is document, where it was initially created, so using "top level jQuery" we don't need to specify top level document.
Have a look at Ben Alman's jQuery postMessage plugin

Can't change innerHtml neither with plain JavaScript not with jQuery

Here is source code of the simple page:
<html>
<head>
<title>Test</title>
<script src="jquery-1.4.2.js" type=text/javascript></script>
</head>
<body>
<div id="divText">Original</div>
<script type="text/javascript">
var vText = document.getElementById('divText');
vText.innerText = 'Changed';
alert(vText.innerHTML);
$('divText').text = 'Changed with jQuery';
alert(vText.innerHTML);
</script>
</body>
</html>
"jquery-1.4.2.js" file is in the same folder.
Both alerts display "original" text, text in browser also "Original"...
What is wrong with my code? Any thoughts are welcome.
1. A quick google ( took me 2 seconds ) reveals text is a function, not a property. Use it like .text('lol') as the example directly from the API.
http://api.jquery.com/text/
2. innerText isn't available in every browser/DOM property.
As you pointed out in the title you'll be wanting to change the inner html. You'll also need the $('#divText') selector to get to the div with jQuery.
<html>
<head>
<title>Test</title>
<script src="jquery-1.4.2.js" type=text/javascript></script>
</head>
<body>
<div id="divText">Original</div>
<script type="text/javascript">
var vText = document.getElementById('divText');
vText.innerHTML = 'Changed';
alert(vText.innerHTML);
alert($('#divText'));
$('#divText').html('Changed with jQuery');
alert(vText.innerHTML);
</script>
</body>
</html>

Categories

Resources