How do I select a span content, using jquery? - javascript

I have the next html.
I need to get a span text content of 'Jan' and '2017' in a onclick function.
I canĀ“t use contains('Jan') or contains('2017') because that values can change at runtime.
I tried the next but no success.
div.relative {
position: relative;
top: 30px;
right: 30px;
bottom: 30px;
left: 30px;
border: 3px solid #73AD21;
}
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
function ClockClicked(){
var smonth=$("span.spanmonth").filter(function() { return ($(this).text()) });
var syear=$("span.spanyear").filter(function() { return ($(this).text()) });
alert(smonth+'-'+ syear);
};
</script>
</head>
<body>
<div class="myclock">
<div class="controls">
<a class="pull-left">
<div class="btn btn-primary" onclick="ClockClicked()">Click me</div>
</a>
<h4>
<span class="spanmonth" Jan></span> - <span class="spanyear" 2017></span>
</h4>
</div>
</div>
</body>
</html>
html:
I have used this function:

As per statement get a span text content of 'Jan' and '2017' I am assuming HTML content is
<span class="spanmonth" >Jan</span> - <span class="spanyear">2017</span>
You need to use .text(). No need of using .filter()
var smonth=$("span.spanmonth").text();
var syear=$("span.spanyear").text();
alert(smonth+'-'+ syear);
I would recommend you to use unobtrusive event handler as #Rory McCrossan suggested.

Firstly note that your HTML is invalid. The Jan and 2017 values should be wrapped in the span elements, not set as attributes of it - which itself is invalid.
Secondly it's better practice to use an unobtrusive event handler over the now outdated on* event attributes. Within that event handler you can use the this keyword to reference the element that raised the event and traverse the DOM to find the span you require. In this case, closest() and find() would suit your needs. Try this:
$('.myclock .btn').click(function() {
var $clock = $(this).closest('.myclock');
var month = $clock.find('.spanmonth').text();
var year = $clock.find('.spanyear').text();
console.log(month, year);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="myclock">
<div class="controls">
<a class="pull-left">
<div class="btn btn-primary">Click me</div>
</a>
<h4>
<span class="spanmonth">Jan</span> - <span class="spanyear" >2017</span>
</h4>
</div>
</div>

Note: Your html is invalid as you have 'Jan' between the < and > tag instead of text within the span.
In any case, you can try the filter -contains':
$( "span.spanmonth").filter(":contains('2017')" );
https://api.jquery.com/contains-selector/

Related

Add an element (input) in div where the js function has been fired

I'd like to insert an input in an adjacent div where the JS function has been fired.
JavaScript: to add an element (input in this case)
jQuery: to detect where the javascript function has been fired.
The issues I'm facing :
The input is created after the second click.
All the inputs move from one div to another on each click ...
I don't understand why this happens! Do you guys have an idea why everything messes up? Thanks a lot.
var ct = 0; // numeric identifier for training section
var lec = 0; // numeric identifier for lectures
function addLecture() {
lec++;
var div = document.createElement('div');
div.setAttribute('id', 'lecture'.concat(lec))
var input = document.createElement('input');
lecture.setAttribute('type', 'text')
div.appendChild(input)
var id;
jQuery('.info_container').click(function(id) {
var id = jQuery(this).attr("id");
document.getElementById(id).querySelector('[id ^= "lectures_container"]').insertAdjacentElement('beforeend', div);
});
}
[id^="row"] {
padding: 10px;
margin: 10px;
background-color: gray;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<div id="row-4" class="info_container">
<div id="lectures_container4">
</div>
<a class="btn btn-add" href="javascript:addLecture()"><span class="fa fa-plus"></span> Add an input</a>
</div>
<div id="row-5" class="info_container">
<div id="lectures_container5">
</div>
<a class="btn btn-add" href="javascript:addLecture()"><span class="fa fa-plus"></span> Add an input</a>
</div>
Full code and live example in the JS fiddle right here: https://jsfiddle.net/t7x350d9/
Your code is much more complicated than it needs to be.
Firstly when dealing with repeated HTML structures do not use id attributes. Use the same class on them all to group them. If you need to identify each one, listen for the event and use the target to determine which element was interacted with. In the example below this can be done through the target property of the event which is raised.
Secondly, to achieve your goal simply use an unobtrusive event handler in your JS (not an onclick attribute in the HTML) and append() the new HTML. Try this:
jQuery($ => {
$('.info_container .btn').on('click', e => {
e.preventDefault();
$(e.target).closest('.info_container').find('.lectures_container').append('<div class="lecture"><input type="text" /></div>');
});
});
.info_container {
padding: 10px;
margin: 10px;
background-color: gray;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<div class="info_container">
<div class="lectures_container"></div>
<a href="#" class="btn btn-add">
<span class="fa fa-plus"></span> Add an input
</a>
</div>
<div class="info_container">
<div class="lectures_container"></div>
<a href="#" class="btn btn-add">
<span class="fa fa-plus"></span> Add an input
</a>
</div>

jQuery: find H2 id and append link with same id

I have the following code and I want for every H2 with id attribute I would create an anchor link. I can not get it to work properly...
<div id="mydiv">
<h2 id="first">first</h2>
<h2>second</h2>
<h2 id="third">third</h2>
</div>
.sls {color: red;font-size: 12px;}
$('#mydiv')
.find('h2[id]')
.append(' <a href="http://www.test.com/page.html#'+ $('h2[id]')
.attr('id') +'" class="sls">Link</a>');
https://jsfiddle.net/ivanionut/1ohh2hws/
Thanks for your help.
Do you want something like this?
$('#mydiv').find('h2[id]').each(function () {
$(this).append(' Link');
});
.sls {
color: red;
font-size: 12px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="mydiv">
<h2 id="first">first</h2>
<h2>second</h2>
<h2 id="third">third</h2>
</div>
In your append call you are using $('h2[id]).attr() this will get the attribute of the first element in the set found, so it will always get the id for the first h2. Update the code to use this in the append using a function, like so:
.append(function() {
return 'Link'
});
https://jsfiddle.net/1ohh2hws/2/

avoid multiple cloned or duplicated div on button click and insertAfter the same last cloned div once

I have a div and I want to duplicate it. I mean that I wanted the same div to be duplicated once. I have used such code for it.
$("#btnAddRules").click(function(){
$(".div1_section").clone().insertAfter($(".div1_section"));
});
But, when click on the button again and again , it is adding multiple of the DIVs and I wanted only one div to be inserted after the last div.
<div class="col-md-8">
<div class="row div1_section">
<div class="col-md-6">
<label>hey hey hey</label>
<select class="form-control">
<option>klklk</option>
<option>huhuuh</option>
</select>
<br/>
</div>
<div class="col-md-6">
<label>abc</label>
<div class="input-group-currency">
<span class="currency">pk</span>
<input type="text" class="form-control input-currency" name="start" value="20'000" style="float:left">
</div>
</div>
</div>
Hope to hear from you, soon.
Thanks
Use last() to target just the last element from the collection:
$("#btnAddRules").click(function() {
$(".div1_section").last().clone().insertAfter($(".div1_section").last());
});
.div1_section {
line-height:50px;
margin:20px 0;
padding:0 20px;
background:tomato;
color:white;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="btnAddRules">Add More Rules</button>
<div class="div1_section">Original</div>
Remove the event listener after the first click like this:
var callback = function () {
document.getElementById('btnAddRules').removeEventListener('click', callback);
$(".div1_section").clone().insertAfter($(".div1_section"));
}
document.getElementById('btnAddRules').addEventListener('click', callback);
Sorry for using vanilla JS and your jquery, I'm more used to write vanilla JS.
Use last() to target just the last element from the collection and after() to put div after a div:
$("#btnAddRules").click(function(){
$(".div1_section").last().after($(".div1_section").last().clone());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="div1_section" >
Hi this is testing
</div>
<button type="button" id="btnAddRules">
Add DIV
</button>

find is not working to select data from dom in jquery

what i need
i need to access href from class events_links .
html code
<div class="row flush frt" itemscope="" itemtype="http://schema.org/Event">
<div class="12u">
<div class="evntblk">
<a itemprop="url" class="events_links" href="/dailymail-ideal-homeshow">
<h2 class="lnh1" itemprop="name">Ideal Home Show - London</h2>
</a>
<div style="display:block; float:right; width:auto; color:#7c7c7c;"></div>
<span itemprop="startDate" class="startdates" content="2015-03-20">20 Mar-06 Apr 2015</span><span itemprop="endDate" class="enddates" content="2015-04-06"></span><br><span itemprop="location" itemscope="" itemtype="http://schema.org/Place"><span itemprop="name" style="display:none">Olympia Exhibition Centre</span><span itemprop="address" itemscope="" itemtype="http://schema.org/PostalAddress"><span itemprop="addressLocality" class="eventcity">London</span>,
<span itemprop="addressCountry" class="eventcountry">UK</span></span></span>
<p class="tal" style="overflow:hidden">The ZEE Asian Pavilions are a celebration of British Asian Culture, that encapsulates Asian food, Asian fashion,...<br><span style="background: none repeat scroll 0 0 #ECECEC; border-radius: 5px; color: #333333; display: inline-block; font-size: 0.8em;line-height: 13px; margin: 5px 2px 0 0 !important; padding: 5px 8px;">Home Furnishings & Home Textiles</span></p>
</div>
<div class="row flush footer"><div class="12u"><a class="button button-blue small">View Details</a></div></div>
js code
$('.small').click(function()
{
alert("test");
window.location.href = $(this).find(".events_links").attr("href");
});
snapshot of html element
i have tried to access with .parent() but it not working.
o/p
i need to access events_links class by click on class small so that i
would get href from that html element.
any suggestion are most welcome.
Simple solution to get only the related url is with parent() function:
$('.small').click(function()
{
window.location.href = $(this).parent().parent().parent().find(".events_links").attr("href");
});
since you are three levels underneath.
find() will start searching from the given object downwards in hierarchy.
BUT as stated before, this will fail, as soon as you change your html layout and maybe drop or add a div container.
it would be much better practice to give your divs containing the urls unique id's or store the link with the data attribute of the button.
So for example if in your HTML Code you had this
<div id="link12" class="event_links" href="FOUND THIS!">
<div class="whatever">
<div class="anotherone">
<div class="button small" data-link="link12" data-href="FOUND THIS HERE TOO!">
CLICK HERE
</div>
</div>
</div>
</div>
Then your click code could access URL via 2 methods:
$('.small').click(function()
{
// METHOD 1: get by storing unique id with button
alert($('#'+$(this).attr('data-link')).attr("href"));
// METHOD 2: same effect, but shorter storing href at button
alert($(this).attr('data-href'));
});
try this
$('.small').click(function() {
alert("test");
window.location.href = $(".events_links").attr("href");
});
I would suggest data-attr in this case, where you do not want to depend on code structure and css.
<div class="row flush footer">
<div class="12u">
<a class="button button-blue small" data-relative-path="some-location">View Details</a>
</div>
</div>
And
$('.small').click(function(){
window.location.href = $(this).data('relative-path');
});
You can try this one:
$('.small').click(function() {
alert("test");
window.location.href = $(".evntblk .events_links").attr("href");
});
If you need to get only href of the single .event_links object in the current .box.panel do:
$('.small').click(function()
{
alert("test");
window.location.href = $(this).closest(".box.panel").find(".events_links").attr("href");
});
closest will get you the first parent element that matches the selector. This way if you have any other .event_links that are not into this panel, they'll be skipped. If you use parent() you'll be forced to keep the same HTML sturcture between the .small and it's parents.
First of all it's bad practice to try and load a url based on a css class. That is because it is probable you use css classes repeatedly on a single page, resulting in multiple anchor selections.
However you could do the following:
$('.small').click(function()
{
var btn = $(this);
// find the closest element of click button with class 'event-block'
// find the element with class 'events_links'
// change window location to value at href
window.location.href = btn.closest('.event-block').find('.events_links').attr("href");
});

Cleaner way to reference the selector name

The code below works, but I suspect there is be a cleaner.
Any alternative to reference the selector names, specially the first differently?
jQuery
$(".add_one_more").click(function(){
var themsg = $(this).parent().attr('id');
$('"#'+themsg+'"').stop().fadeOut("slow",function(){
$("#entry_area").stop().fadeIn("slow");
});
return false;
});
HTML
<div id="entry_area">Form Goes Here</div>
<div id="msg0">
<span style="font-size: 130%; color: green;">One Message</span>
Try Again
</div>
<div id="msg1" style="width: 550px;">
<span style="font-size: 130%; color: red;">Another Message</span>
Try Again
</div>
You shouldn't need to select the parent and get its ID.
$(".add_one_more").click(function(){
$(this).parent().stop().fadeOut("slow",function(){
$("#entry_area").stop().fadeIn("slow");
});
return false;
});
I like quite a bit of what you're doing, but I'll add my thoughts on making your js more resilient to getting pieces moved around.
JS
$("#entry_area, div.message").bind("stop", function(evt){
$(this).stop().fadeIn("slow");
} );
$(".add_one_more").click(function(evt){
$(this).closest("div.message").trigger("stop");
$("#entry_area").trigger("stop");
return false;
});
html
<div id="entry_area">Form Goes Here</div>
<div id="msg0" class="message">
<span style="font-size: 130%; color: green;">One Message</span>
Try Again
</div>
<div id="msg1" class="message" style="width: 550px;">
<span style="font-size: 130%; color: red;">Another Message</span>
Try Again
</div>
Actually, I'd say you don't need to store the id if you don't re-use it after all, try:
$(".add_one_more").click(function(){
var $parent = $(this).parent();
$parent.stop().fadeOut("slow",function(){
$("#entry_area").stop().fadeIn("slow");
});
return false;
});
or even shorter without storing the jquery object in a var ([EDIT] This is exactly what Daniel posted while I was writing this).
How about
var themsg = $(this).parent();
themsg.stop() ...

Categories

Resources