How should I populate nested elements using jquery? - javascript

I want to display NEWS headines on my website. I want to populate it using Jquery. I have written the code but nothing is displayed on webpage.
HTML code:
<div class="col-md-4">
<div id="sidebar-wrapper">
<ul class="sidebar-nav">
<strong>Latest Headines</strong>
<li>
<a href="" class="title">
<h2> </h2>
</a>
</li>
<li>
<a href="" class="title">
<h2> </h2>
</a>
</li>
<li>
<a href="" class="title">
<h2> </h2>
</a>
</li>
<li>
<a href="" class="title">
<h2> </h2>
</a>
</li>
<li>
<a href="" class="title">
<h2> </h2>
</a>
</li>
</ul>
</div>
</div>
JS code:
$(document).ready(function() {
$.getJSON('https://newsapi.org/v1/articles?source=techcrunch&sortBy=top&apiKey=my-api-key',function(json) {
console.log(json);
console.log(json.articles.length);
function headlines (json) {
for(var i=0;i<5;i++){
$('.sidebar-nav li a h2').eq(i).html(json.articles[i].title);
}
}
});
});
I have made a class called sidebar then inside class I have placed list and anchor followed by <h2></h2> tag. I want to populate h2 tag with NEWS headlines but nothing is displayed on my webpage.

$('.sidebar-nav li').eq(i).find('h2').html(...)
li is the Nth element you're looking for, not h2.
For that matter, you should cache the nav element or the lis, to avoid hammering the DOM :
var $lis = $('.sidebar-nav li')
for(var i=0;i<5;i++){
$lis[i].find('h2').html(json.articles[i].title);
}

First of all: You don't call your function headlines so nothing goes to output ;)
Second one:
$('.sidebar-nav li a h2').eq(i)
will only work for the first item i think, because there is only 1 H2-Tag within the a-Tag.
I suggest giving all H"-Tag a class like ".headline" and itterating over them.
I hope this helps ;)

Related

jquery clone the content of a div on page load

I would like to clone an element inside a div and append it to another div without any click event, on page load. This is my code:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul class="hs-search-results__listing">
<li>
Search Title
<p class="more-link-container">
</p>
</li>
<li>
Search Title
<p class="more-link-container">
</p>
</li>
</ul>
<script>
$('.hs-search-results__listing li').each(function(){
$(this).find('.hs-search-results__title').clone().appendTo(".more-link-container");
});
</script>
I am trying the above but it is not working.
In each iteration you are appending to all the elements with class more-link-container available in the DOM. You should append the element only to the relevant p element.
Change
.appendTo(".more-link-container")
To
.appendTo($(this).find(".more-link-container"))
$('.hs-search-results__listing li').each(function(){
$(this).find('.hs-search-results__title').clone().appendTo($(this).find(".more-link-container"));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul class="hs-search-results__listing">
<li>
Search Title
<p class="more-link-container">
</p>
</li>
<li>
Search Title
<p class="more-link-container">
</p>
</li>
</ul>

jQuery if list item contains ''-" .remove()?

I am restyling a list of related articles in a li and I would like to remove the "-" between the a tag and span without messing with the original content on the page (links). I must use jQuery and I'm not sure if there is a simple way of doing this.
<div class="related-articles card">
<h3 class="h2">
<i class="fa fa-book text-brand-primary-dark"></i> Related Articles
</h3>
<ul>
<li>
Title One
-
<span> Some Related Preview Text... </span>
</li>
<li>
Title Two
-
<span> Some Related Preview Text... </span>
</li>
<li>
Title Three
-
<span> Some RelatedPreview Text... </span>
</li>
</ul>
Here is my solution, get the children elements and assign it back, so the plain text present (-) will get removed!
$('.related-articles li').each(function() {
$(this).html($(this).children());
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="related-articles card">
<h3 class="h2">
<i class="fa fa-book text-brand-primary-dark"></i> Related Articles
</h3>
<ul>
<li>
Title One -
<span> Some Related Preview Text... </span>
</li>
<li>
Title Two -
<span> Some Related Preview Text... </span>
</li>
<li>
Title Three -
<span> Some RelatedPreview Text... </span>
</li>
</ul>
One way would be to loop through each <li>, extract the <a> and <span> elements and stitch them together manually, like this:
$("ul > li").each( (i, li) => {
const $li = $(li);
const $a = $li.find("a");
const $span = $li.find("span");
//create a temp element with just the <a> and <span>
const $tempItem = $("<li></li>");
$tempItem.append( $a ).append( $span );
//copy new HTML into old element
$li.html( $tempItem.html () );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li>
Title One
-
<span> Some Related Preview Text... </span>
</li>
<li>
Title Two
-
<span> Some Related Preview Text... </span>
</li>
<li>
Title Three
-
<span> Some RelatedPreview Text... </span>
</li>
</ul>
One option is:
$('.related-articles li a').map(function() {
return this.nextSibling;
}).remove();

Jquery append and modify each of same class

I am trying to take content from a nav bar, and then modify and append it to a mobile menu. The nav bar html looks like
<div id="top_bar" class="nav">
<div class="container">
<div class="row">
<nav class="clearfix">
<span>My Account</span>
<span> Rewards</span>
<span>Customer Service</span>
</nav>
</div>
</div>
</div>
I need to append the anchors above to the following menu and have them work in the format below.
<ul id="stmobilemenu" class="visible-xs visible-sm show">
<li class="stmlevel0">first</li>
<li class="stmlevel0">second</li>
<li class="stmlevel0">third</li>
</ul>
I tried to do this like
var add_to_menu;
$('#top_bar nav a').each(function(){
var line = '<li class="stmlevel0">';
$(this).addClass('ma_level_0');
line += $(this).html();
line += '</li>';
add_to_menu += line;
})
$('#stmobilemenu').append(add_to_menu);
The result of this was it added undefined, then it added only the content
so appeneded was in this type of format.
<li class="stmlevel0"><span>My account</span></li>
what I want it to add is in this type
<li class="stmlevel0"><span>My account</span></li>
Another thing I tried was
$('#stmobilemenu').append(
$('#top_bar nav a').each(function(){
$(this).prepend('<li class="stmlevel0">');
$(this).addClass('ma_level_0');
$(this).append('</li>');
}));
I had a few problems with this though, first of all the append and prepend were not actually surrounding the html I want. It comes out like
<a href="http://127.0.1.1:8080/my-account" class="top-bar-link ma_level_0">
<li class="stmlevel0"></li>
<span>My account</span>
</a>
So I need that li to actually surround the a. Also it actually removed the content of #top_bar nav a from its original spot, which is not what I want it to do. I want it only to copy and add to the mobile menu. Can someone help?
Use clone() to make a copy of each <a>
var $mobMenu= $('#stmobilemenu');// store reference to menu element
$('#top_bar nav a').each(function(){
var $link = $(this).clone().removeClass().addClass('ma_level_0');
$('<li class="stmlevel0">').append($link).appendTo( $mobMenu);
});
var anchors = $('#top_bar nav').children();
anchors.each(function(){
var $this = $(this),
$li = $('<li class="stmlevel0"></li>');
$this.removeClass().addClass('ma_level_0').appendTo($li);
$li.appendTo('#stmobilemenu');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="top_bar" class="nav">
<div class="container">
<div class="row">
<nav class="clearfix">
<span>My Account</span>
<span> Rewards</span>
<span>Customer Service</span>
</nav>
</div>
</div>
</div>
<ul id="stmobilemenu" class="visible-xs visible-sm show">
<li class="stmlevel0">first</li>
</ul>

Traversing up and finding a child element with attribute equal to a specific value

I have a list UL that contains an element article that has an attribute data-level. I am traversing in Javascript through the articles. I am adding a replyto symbol to comments that have a data-level larger than 1, but to get the username of the parent, I need to traverse the comment list up and find an article element that has data-level="0" and get the username from that element.
I can't use jquery closest() because it doesn't check inside the element. If I use parent().parent() it will run closest() on the parent, which is also not good.
How can I run a closest() function or something familiar on the article element (red arrow in the image) to find the first article element above it that has its attribute equals to 0 (data-level="0").
Here's an the HTML code:
<ul>
<li>
<article itemprop="comment" itemscope="itemscope" itemtype="http://schema.org/Comment" data-user-id="28" id="comment-40" data-comment-id="40" class="comment-wrapper" data-level="0">
<header>
<p class="comment-title"> <span class="submitted-by"><span itemprop="author" itemscope="itemscope" itemtype="http://schema.org/Person"><span itemprop="name">yariv</span></span><span class="karma" title="Karma"><span class="fa fa-star"></span>0</span> •
<meta itemprop="dateCreated" content="2015-12-09T06:28:59Z">
<time class="date-submitted" datetime="2015-12-09T06:28:59Z">7 months ago</time>
</span>
</p>
</header>
<div class="comment-content">
<p class="comment-body" itemprop="text">fgdfg </p>
</div>
<div class="comment-options"><span data-already-voted="false" class="upvote"><span class="fa fa-thumbs-up"></span><span class="upvote-num" itemprop="upvoteCount">1</span></span><span class="reply" data-user-id="28" data-comment-id="40">Reply</span><span class="flag-comment">Flag</span>
</div>
<div class="notification"></div>
</article>
</li>
<li>
<article itemprop="comment" itemscope="itemscope" itemtype="http://schema.org/Comment" data-user-id="28" id="comment-42" data-comment-id="40" class="comment-wrapper" data-level="2">
<header>
<p class="comment-title"> <span class="submitted-by"><span itemprop="author" itemscope="itemscope" itemtype="http://schema.org/Person"><span itemprop="name">yariv</span></span><span class="karma" title="Karma"><span class="fa fa-star"></span>0</span> •
<meta itemprop="dateCreated" content="2015-12-09T06:28:59Z">
<time class="date-submitted" datetime="2015-12-09T06:28:59Z">7 months ago</time>
</span>
</p>
</header>
<div class="comment-content">
<p class="comment-body" itemprop="text">fgdfg </p>
</div>
<div class="comment-options"><span data-already-voted="false" class="upvote"><span class="fa fa-thumbs-up"></span><span class="upvote-num" itemprop="upvoteCount">1</span></span><span class="reply" data-user-id="28" data-comment-id="40">Reply</span><span class="flag-comment">Flag</span>
</div>
<div class="notification"></div>
</article>
</li>
</ul>
Note: There can be several comments with data-level="0" and I need the closest one above the article I am currently checking. In other words. For an <article> element, I need to find the closest (from above) <article> element that exists above it inside an li element that it's attribute data-level equals to zero.
You can use closest to get the li around the reply, and then prevAll with a :has([data-level=0]) filter, and then first to get the nearest (prevAll returns them in order of nearness rather than the usual document order):
var main = startingElement
.closest("li")
.prevAll(":has([data-level=0])")
.first()
.find("[data-level]");
Simplified example:
// Get our starting point:
var startingElement = $("#start");
// Find the "nearest" data-level=0
var main = startingElement
.closest("li")
.prevAll(":has([data-level=0])")
.first()
.find("[data-level]");
// Show what we got
console.log(main.text());
<ul>
<li>
<div data-level="0">first level 0</div>
</li>
<li>
<div data-level="1">first level 1</div>
</li>
<li>
<div data-level="2">first level 2</div>
</li>
<li>
<div data-level="0">second level 0</div>
</li>
<li>
<div data-level="1">second level 1</div>
</li>
<li>
<div data-level="2" id="start">second level 2</div>
</li>
<li>
<div data-level="0">third level 0</div>
</li>
<li>
<div data-level="1">third level 1</div>
</li>
<li>
<div data-level="2">third level 2</div>
</li>
</ul>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Note how our starting point was the li two siblings away from the one containing data-level="0", but we skipped the one in-between because it didn't match the :has condition.
To add a reply widget to each comment as mentioned, I'd do something like this. Keep in mind that each related comment references the original w/ [data-comment-id]
$(function() {
$("[data-level][data-level!='0']").each(function() {
var id = $(this).data('commentId'),
$comment = $('#comment-'+ id +''),
author = $comment.find('[itemprop="name"]').text();
$('<span> Reply to: </span>')
.appendTo($(this))
.append($(''+author+''));
});
})

How to select element inside first-child selector jquery

Here our simple code snippet of jquery, where we want to select the p element, but what am i writing is not correct, so help us to get them.
<div class="first">
<ul class="first_ul">
<li class="first_li">
<a href="javascript:void(0)">
<div class="hello"></div>
<p class="firstP" url="hello.html">Content of First Paragrph</p>
</a>
</li>
<li class="second_li">
<a href="javascript:void(0)">
<div class="hello"></div>
<p class="firstP" url="hello2.html">Content of Second Paragrph</p>
</a>
</li>
</ul>
</div>
Here , what i am doing
$('.fist_ul .first_li:first-child p');
and actually we want to get the attribute of p element url
Thanks.
$('.first_ul .second_li p');
Seems there was misspell. And your code is not semantic, I mean, inside the <li> there is another <li> it is incorrect.
You have incorect selector . it should use :
$('.first_ul .first_li:first-child p');
Working Demo
You can try with this
$(".first_ul li").find('p')
you can try like this
$('.first_ul .first_li p').attr('url'); // for only <P> of first li's url
$('.first_ul .second_li p').attr('url'); // for only <P> of second li's url
// for all the <p> you have used in all the <li>s
$('.first_ul li p').each(function(k,v){
var wq = $(v).attr('url');
console.log(wq);
});

Categories