I'm try to catch 'banner name' in under code.
<div class = 'pdf-area'>
<ul class = 'pdf list'>
<li>
<span class="icon-left"></span> 'banner name'
</li>
</ul>
</div>
and here is my try.
$("div.pdf-area ul a").click(function(i) {
var txt = $(i.target).text();
console.log(txt);
});
When I run this code, I don't get the value I want.
How can I extract 'baaner name'?
(href= # -> it's not my code and don't have any autohrity that can modify this code . I only can extract value in this condition.)
You do not need to add the click event by using the selector. Simply pass this as the first parameter. Then inside the function use find() on that object to target the span.
Try the following:
function pdfDownload(el, link){
var name = $(el).find('span.icon-left').text();
console.log(name);
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class = 'pdf area'>
<ul class = 'pdf list'>
<li>
<span class="icon-left"> 'banner name'</span>
</li>
</ul>
</div>
OR: If you do not want to change the HTML
$(".pdfarea > ul a > span").click(function() {
var txt = $(this).text();
console.log(txt);
});
function pdfDownload(){}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class = 'pdfarea'>
<ul class = 'pdflist'>
<li>
<span class="icon-left"> 'banner name'</span>
</li>
</ul>
</div>
If the banner name outside the span try the following:
$("div.pdf-area ul a").click(function() {
var txt = $(this).text();
console.log(txt);
});
function pdfDownload(){}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class = 'pdf-area'>
<ul class = 'pdf list'>
<li>
<span class="icon-left"></span> 'banner name'
</li>
</ul>
</div>
<div class = 'pdf-area'>
<ul class = 'pdflist'>
<li>
<span class="icon-left"> 'banner name'</span>
</li>
</ul>
</div>
$(document).on('click','.pdflist a',function(){
alert($(this).text());
})
Above click event will give the text on the current element
Fiddle : https://jsfiddle.net/gokulmaha/vt3b0keu/2/
You can remove the $("div.pdf-area ul a").click(function(i).. and create pdfDownload function which will handle both
function pdfDownload(e, path) {
console.log(path)
e.preventDefault();
var txt = $(e.target).text();
console.log(txt);
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='pdf-area'>
<ul class='pdf list'>
<li>
<span class="icon-left"> 'banner name'</span>
</li>
</ul>
</div>
Hi Try this -
$("div.pdf-area ul a").click(function(i) {
var txt = $("div.pdf-area > ul.list > li a span.icon-left").text();
console.log(txt);
});
Related
The folliwing code is working ONLY with the getElementById method, but i need it to works even in the case there is not an ID on element.
My HTML is:
<div id="container">
<ul class="menu">
<li>
<ul class="submenu">
<li>text i have to get</li>
</ul>
</li>
</ul>
</div>
My JS is:
<script>
var el = document.getElementById("pid");
el.onclick = function what_to_do(){
var theText = this.innerHTML;
alert(theText);
</script>
So i need to get the text in the deepest nested LI element that has no ID when the user clicks over it.
usually with jquery i can make $("#container ul li ul li").on("click, ...
but i am trying to work with pure javascript (vanilla js).
Is there anyone else that can help me?
Thanks in advance
You can use document.querySelectorAll().
Note: You can't just set event to the document.querySelectorAll() like jQuery you need to loops through whole array
const items = document.querySelectorAll('li > ul > li');
items.forEach(item => {
item.addEventListener('click',(e)=>{
console.log(e.target.textContent);
}
)
})
<div id="container">
<ul class="menu">
<li>
<ul class="submenu">
<li>text i have to get</li>
</ul>
</li>
</ul>
</div>
use document.querySelector
var el = document.querySelector("#container > .menu > li > .submenu > li");
el.onclick = function what_to_do(){
var theText = this.innerHTML;
alert(theText);
}
<div id="container">
<ul class="menu">
<li>
<ul class="submenu">
<li>text i have to get</li>
</ul>
</li>
</ul>
</div>
I want to display json.articles[i].title of each news on my website here is my screenshot of website and my code:
In main.js:
(function() {
$.getJSON('https://newsapi.org/v1/articles?source=techcrunch&sortBy=top&apiKey=my-api-key', function(json) {
$("#sidebar-wrapper li").each(function() {
$('li').html(json.articles[0].titles)
});
});
})();
My HTML file :
<div id="sidebar-wrapper">
<ul class="sidebar-nav">
<strong>Latest Headines</strong>
<li>
Your news title
</li>
<li>
Your news title
</li>
<li>
Your news title
</li>
<li>
Your news title
</li>
<li>
Your news title
</li>
</ul>
</div>
Here is my screenshot of website I want to display each news title from json.articles[].title instead of "Your news title".(For clarification see screenshot and HTML code).
Try Below Code
(function () {
$.getJSON('https://newsapi.org/v1/articles?source=techcrunch&sortBy=top&apiKey=045089075bc74354be01b34f6335d32b', function (json) {
var html = "";
$(json.articles).each(function (index, value) {
$(".sidebar-nav").append("<li><a href='"+value.url+"'>" + value.title + "</a></li>");
});
});
})();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="sidebar-wrapper">
<ul class="sidebar-nav">
</ul>
</div>
If all you want is to iterate through the articles you can use an iterator index and keep incrementing it. Something like this.
(function(){
var i = 0;
$.getJSON('https://newsapi.org/v1/articles?source=techcrunch&sortBy=top&apiKey=045089075bc74354be01b34f6335d32b',function(json) {
$("#sidebar-wrapper li").each(function(){
$('li').html(json.articles[i++].titles)
});
});
})();
But you it would be better to iterate over the articles object and create lists dynamically.
You should dynamically create the LI elements, as the no of article from JSON response may vary.
To create element use jQuery(html)
//Cache the ul element
var ul = $("#sidebar-wrapper ul.sidebar-nav");
//iterate the articles
$.each(json.articles, function(index, article) {
//Create anchor
var anchor = $('<a>', {
href: article.url,
text: article.title
});
//Create LI and append anchor after append the LI to UL
$('<li>').append(anchor).appendTo(ul);
});
(function() {
$.getJSON('https://newsapi.org/v1/articles?source=techcrunch&sortBy=top&apiKey=045089075bc74354be01b34f6335d32b', function(json) {
var ul = $("#sidebar-wrapper ul.sidebar-nav");
$.each(json.articles, function(index, article) {
var anchor = $('<a>', {
href: article.url,
text: article.title
});
$('<li>').append(anchor).appendTo(ul);
});
});
})();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="sidebar-wrapper">
<strong>Latest Headines</strong>
<ul class="sidebar-nav">
</ul>
</div>
You can also update li data by using class
Try This
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script> $(document).ready(function(){
$.getJSON('https://newsapi.org/v1/articles?source=techcrunch&sortBy=top&apiKey=045089075bc74354be01b34f6335d32b',function(json) {
var x=document.getElementsByClassName("title");
for(var i=0;i<x.length;i++)
x[i].innerHTML = json.articles[0].titles;
}); }); </script>
<div id="sidebar-wrapper">
<ul class="sidebar-nav">
<strong>Latest Headines</strong>
<li>
Your news title
</li>
<li>
Your news title
</li>
<li>
Your news title
</li>
<li>
Your news title
</li>
<li>
Your news title
</li>
</ul> </div>
I would like to get a certain innerText from a clicked element in a HTML document that I clicked.
The corresponding HTML looks something like this:
!DOCTYPE html>
<html>
<head>
<title>Some title</title>
</head>
<body>
<ul class="categories">
<li>
<a href="http://www.example2.com/1">
<div>
<img src="http://www.example.com/someSource">
<span>First</span>
</div>
</a>
</li>
<li>
<a href="http://www.example2.com/1">
<div>
<img src="http://www.example.com/someSource">
<span>Second</span>
</div>
</a>
</li>
</ul>
</body>
</html>
A Javascript function should return either "First" or "Second" depending on the clicked link.
My basic idea is to add an event listener and use the returned event to get the content of the span element:
function(){
document.addEventListener('click', function(e) {
e = e || window.event;
var spanText= e.path[i].innerText; //Don't know how to assign i correctly
return spanText;
}, false);
}
My problem is that I don't know how to define i or if there is something more suitable than .path[i] to work with. Depending on whether I click the image or the text.
Add the click events to the list items
in the handler, retrieve the 'span' child and get its text
var lis = document.querySelectorAll('.categories li');
lis.forEach(function(el) {
el.addEventListener('click', onClick, false);
})
function onClick(e) {
var li = e.currentTarget;
var span = li.querySelector('span');
console.log(span.innerText);
}
<ul class="categories">
<li>
<a href="http://www.example2.com/1">
<div>
<img src="http://www.example.com/someSource">
<span>First</span>
</div>
</a>
</li>
<li>
<a href="http://www.example2.com/1">
<div>
<img src="http://www.example.com/someSource">
<span>Second</span>
</div>
</a>
</li>
</ul>
function init(){
document.addEventListener('click', function(e) {
var link = e.target.closest('a');
if(!link)return;
e.preventDefault();
var text = link.textContent;
alert(text);
return spanText;
});
}
init();
You can check what concrete element was clicked and then return its text. if you want to have some additional information - use data- attributes and read target.dataset to read it.
document.addEventListener('click', function(e) {
var target = e.target;
if(target.tagName === 'SPAN') {
console.log(target.innerText);
return target.innerText;
}
}, false);
<ul class="categories">
<li>
<a href="#">
<div>
<img src="http://www.example.com/someSource">
<span>First</span>
</div>
</a>
</li>
<li>
<a href="#">
<div>
<img src="http://www.example.com/someSource">
<span>Second</span>
</div>
</a>
</li>
</ul>
If the structure is consistent, then there will always be the same number of <span> elements as <a> elements.
Consequently, if you know the user just clicked on the second <a>, you'll know the <span> you need to return is the second <span>.
Working Example:
var links = document.querySelectorAll('li a');
var spans = document.querySelectorAll('li div span');
function getTextContent(e) {
e.preventDefault();
var linksArray = Array.prototype.slice.call(links);
var index = linksArray.indexOf(this);
console.log(spans[index].textContent);
}
links.forEach(function(link){
link.addEventListener('click', getTextContent, false);
});
<ul class="categories">
<li>
<a href="http://www.example2.com/1">
<div>
<img src="http://www.example.com/someSource">
<span>First</span>
</div>
</a>
</li>
<li>
<a href="http://www.example2.com/1">
<div>
<img src="http://www.example.com/someSource">
<span>Second</span>
</div>
</a>
</li>
</ul>
Sorry for my bad language..
I'm late to reply.
Maybe it will help someone else;
window.addEventListener("click", (event) => { //dblclick
let div = event.target.innerText; // <-- the code you want
window.onClick(div);
});
And..
function onClick(div) {
console.log(`(Tıklandı-Clicked) innerText: ${div}`);
}
the code you want : let div = event.target.innerText;
I have elements which have nested li elements and i made a click function to get the value. Every time i click i am getting the same value again and again.
<script type="text/javascript">
$('.cat-select').on('click',function(){
$('.cat-list').css('display','block');
$('.sub-list').css('display','block');
});
$(document).on('click','.cat-list>li',function(){
var selectedVal = $(this).clone() //clone the element
.children() //select all the children
.remove() //remove all the children
.end() //again go back to selected element
.text(); //get the text of elemen
console.log(selectedVal);
$('.cat-select').text(selectedVal);
});
</script>
<div class="form-group">
<label for="input-placeholder" class="col-sm-2 control-label"></label>
<div class="col-sm-10">
<style type="text/css">
.cat-list, .sub-list{ display: none; }
</style>
<div class="cat-group">
<button class="cat-select" type="button">Select Category</button>
<ul class="cat-list">
<li class="have-child">Electronics
<ul class="sub-list">
<li class="have-child"> Mobiles & Tablets
<ul class="sub-list">
<li>Mobiles</li>
<li>Tablets</li>
<li class="have-child">Accessories</li>
<ul>
<li>Power Bank</li>
<li>Phone Cases</li>
</ul>
</ul>
</li>
<li class="have-child">Cameras
<ul class="sub-list">
<li>DSLRs</li>
<li>Drones</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
</div>
</div>
Every time i click i am getting the same value
https://jsfiddle.net/yx4Ldt80/
The issue you see is because you only attach the event handler to the child of the .cat-list through your use of the > operator.
To solve this, remove that from the selector and call stopPropagation() on the event to stop it bubbling up the DOM. Try this:
$(document).on('click', '.cat-list li', function(e) {
e.stopPropagation();
var selectedVal = $(this).clone().children().remove().end().text();
$('.cat-select').text(selectedVal);
})
$('.cat-select').on('click', function() {
$('.cat-list, .sub-list').toggle();
});
$(document).on('click', '.cat-list li', function(e) {
e.stopPropagation();
var selectedVal = $(this).clone().children().remove().end().text();
$('.cat-select').text(selectedVal);
})
.cat-list,
.sub-list {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div class="form-group">
<label for="input-placeholder" class="col-sm-2 control-label"></label>
<div class="col-sm-10">
<div class="cat-group">
<button class="cat-select" type="button">Select Category</button>
<ul class="cat-list">
<li class="have-child">Electronics
<ul class="sub-list">
<li class="have-child">
Mobiles & Tablets
<ul class="sub-list">
<li>Mobiles</li>
<li>Tablets</li>
<li class="have-child">Accessories
<ul>
<li>Power Bank</li>
<li>Phone Cases</li>
</ul>
</li>
</ul>
</li>
<li class="have-child">
Cameras
<ul class="sub-list">
<li>DSLRs</li>
<li>Drones</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
</div>
</div>
Also note that I fixed the HTML in your 'Accessories' ul as it was outside of the parent li.
"Never use" Event.stopPropagation()
The worst thing you can do (as suggested by answers here and around the web) is to use Event.stopPropagation().
Don't use Event.stopPropagation(), well, unless you really know what you're doing.
An Application should be always aware of every event happening in it's context.
Imagine you build a popup, modal, or a custom select-box that needs to close if you click anywhere else in the page. Well, congratulations, a LI element just stopped you from doing so.
Use Event.target instead
function myClickHandler(ev) {
if (ev.target !== this) return; // Ignore if non-this called the event
console.log( this.textContent );
}
Here's an example with your specific use-case:
const $cat = $('.cat-select');
$cat.on('click', function() {
$('.cat-list, .sub-list').toggle();
});
$(document).on('click', '.cat-list li', function(ev) {
if (ev.target !== this) return; // Ignore if non-this called the event
const value = $(this).contents().filter((i, el) => el.nodeType == 3)[0].nodeValue;
$cat.text(value);
});
// Than, 3000 lines later... THANK YOU BECAUSE:
$('body').on('click', function() {
// Close a popup or something
console.clear(); console.log(`YEY I registered an event!
Thank you for not using Event.preventDefault()`);
});
.cat-list,
.sub-list {
display: none;
}
<div class="form-group">
<label for="input-placeholder" class="col-sm-2 control-label"></label>
<div class="col-sm-10">
<div class="cat-group">
<button class="cat-select" type="button">Select Category</button>
<ul class="cat-list">
<li class="have-child">Electronics
<ul class="sub-list">
<li class="have-child"> Mobiles & Tablets
<ul class="sub-list">
<li>Mobiles</li>
<li>Tablets</li>
<li class="have-child">Accessories</li>
<ul>
<li>Power Bank</li>
<li>Phone Cases</li>
</ul>
</ul>
</li>
<li class="have-child">Cameras
<ul class="sub-list">
<li>DSLRs</li>
<li>Drones</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Get the clicked element based the event.target property. Although you can avoid the clone by contents() and filter() methods which help to filter out text nodes.
$(document).on('click', 'li', function(e) {
// if target element is not `li` tag then get closest li tag
var selectedVal = (e.target.nodeType == 'LI' ? $(e.target) : $(e.target).closest('li'))
.contents() // get all children nodes
.filter(function() { // filter out text nodes
return this.nodeType === 3;
}).text(); // get text content
$('.cat-select').text(selectedVal);
})
$(document).on('click', 'li', function(e) {
// if target element is not `li` tag then get closest li tag
var selectedVal = (e.target.nodeType == 'LI' ? $(e.target) : $(e.target).closest('li'))
.contents() // get all children nodes
.filter(function() { // filter out text nodes
return this.nodeType === 3;
}).text(); // get text content
$('.cat-select').text(selectedVal);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group">
<label for="input-placeholder" class="col-sm-2 control-label"></label>
<div class="col-sm-10">
<div class="cat-group">
<button class="cat-select" type="button">
Select Category</button>
<ul class="cat-list">
<li class="have-child">Electronics
<ul class="sub-list">
<li class="have-child">Mobiles & Tablets
<ul class="sub-list">
<li>Mobiles</li>
<li>Tablets</li>
<li class="have-child">Accessories</li>
<ul>
<li>Power Bank</li>
<li>Phone Cases</li>
</ul>
</ul>
</li>
<li class="have-child">Cameras
<ul class="sub-list">
<li>DSLRs</li>
<li>Drones</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
</div>
i hope this one is helping u
$('.cat-select').each(function() {
$(this).on('click', function() {
$('.cat-list').css('display', 'block');
$('.sub-list').css('display', 'block');
});
});
$(document).on('click', function() {
$(this).each('.cat-list li', function() {
var selectedVal = $(this).clone() //clone the element
.children() //select all the children
.remove() //remove all the children
.end() //again go back to selected element
.text(); //get the text of elemen
console.log(selectedVal);
$('.cat-select').text(selectedVal);
});
});
Ok guys, as promised, here is the real deal, first the sample html:
<li data-foo="bar">
<span id="a"></span>
<ul>
<li>
<span id="1"></span>
<ul>
<li>
<span id="b"></span>
</li>
</ul>
</li>
<li>
<span id="2"></span>
<ul>
<li>
<span id="c"></span>
</li>
</ul>
</li>
</ul>
</li>
<li data-foo="bar">
<span id="d"></span>
<ul>
<li>
<span id="3"></span>
<ul>
<li>
<span id="e"></span>
</li>
</ul>
</li>
<li>
<span id="4"></span>
<ul>
<li>
<span id="f"></span>
</li>
</ul>
</li>
</ul>
</li>
I want to get the window to pop up "12", then pop up "34"... so here is my nested functions attempt:
<script>
var poptext = "";
$('li[data-foo=bar]').each(
function () {
$(this li span).each(function () {
poptext = poptext + $(this).attr("id");
}
alert(poptext);
poptext = "";
);
}
);
</script>
This does not seem to be working, I think Jquery might got confused with multiple "this" keywords? Also there could be something wrong with the selector for those spans to begin with.
Thanks guys!
I think you are looking for the direct descendant selector: >
Used like this:
$('li[data-foo=bar]').each(function () {
var poptext = "";
$(this).find('> ul > li > span').each(function () {
poptext = poptext + $(this).attr("id");
});
alert(poptext);
});
Will only select the nodes that are direct children of the previous expression on the left hand side.
A more verbose, but maybe readable version could be:
$(this).children('ul').children('li').children('span') // selects the same
See it in action here: http://jsfiddle.net/xYgJg/
You have syntax errors in your code, $(this li span) should be $('li span', this) also your logic is off, you aren't filtering out the spans with the letter ids.