Can any one tell me, how i can select and alert text "__user_Name_" which is immediate to img with. i am using j query selector.
<div id="side-bar" class="test" style="">
<ul>
<li alt="User options">
<a href="#" name="nav1">
<img alt="USERNAME" src="myprofile.png" style="vertical-align: bottom; border: 0px solid rgb(255, 255, 255);">__user_Name_
</a>
</li>
You can't use a selector, but you can access it vai
var el = $('img').prop('nextSibling')
here el will be a dom element reference, not a jQuery object.
If you just want to read the text then you can use
var text = $('img').text()
I think what you're wanting is the following, though I'm not sure if I've read your question correctly:
To get the text: $('a[name="nav1"]').text()
To set the text: $('a[name="nav1"]').text("New Text")
You could use the .text() method with on the 'a' selector. Something like:
var selected = $('a').text();
alert(selected);
jsFiddle
Related
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/
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/
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");
});
I try to paste text into multiple fields, but the formatting is only cleared on the first element, not the second etc.
I found this question https://stackoverflow.com/a/12028136/3955607 which works fine, but again, on multiple elements it doesnt work.
So I got this HTML
<div style="color:red">Some <em>rich</em> <span style="font-size:2em">HTML</span></div>
<br />
<div style="border:1px solid red" contenteditable></div>
<br />
<div style="border:1px solid red" contenteditable></div>
and this javascript:
document.querySelector("div[contenteditable]").addEventListener("paste", function(e) {
e.preventDefault();
var text = e.clipboardData.getData("text/plain");
document.execCommand("insertHTML", false, text);
});
I have this fiddle http://jsfiddle.net/tdjuc8es/
just copy and paste the Some rich HTML- text and see what happens
Someone who can help me out?
document.querySelector yields one element. You want to use document.querySelectorAll to get all matching elements, and then iterate over that collection.
var editors = document.querySelectorAll('div[contenteditable]');
for(var i = 0, l = editors.length; i < l; i++) {
editors[i].addEventListener('paste', myCustomPasteFunction);
}
Fiddle
If you're used to jQuery, you might think that document.querySelector() fulfils the same kind of function; however, it only returns the first element that matches the selector; instead you should have used document.querySelectorAll() and then used iteration to add your event handlers.
Since you've tagged it as jquery, you could also consider this:
$("div[contenteditable]").on("paste", function(e) {
e.preventDefault();
var text = e.originalEvent.clipboardData.getData("text/plain");
document.execCommand("insertHTML", false, text);
});
div[contenteditable] {
height: 50px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div style="color:blue">Some <em>rich</em> <span style="font-size:2em">HTML</span></div>
<br />
<div style="border:1px solid red" contenteditable></div>
<br />
<div style="border:1px solid red" contenteditable></div>
I'm using e.originalEvent here because the one that jQuery passes you in the event handler is a wrapper object.
It is beacause the document.querySelector only return the first matched element.
You can use document.querySelectorAll instated.
Wish it can help you.
I have a textarea that contains several images. All images have an id and I want to loop through all of those images and check if the need an onclick event (depends on id)
If the do not need a onclick event I need to check if the have one and remove it. If the need I I still need to remove it and add another (because the value of the onclick could be changed)
How can I do this?
<img id="slideShowImage_3" style="border: 1px solid black; cursor: pointer;" title="3" onclick="loadSlideShow('7','open','3','','2')" src="uploads/nieuws/7/1363788115.jpg" alt="3" />
<img id="slideShowImage_3" style="border: 1px solid black; cursor: pointer;" title="3" src="uploads/nieuws/7/1363788115.jpg" alt="3" />
http://jsfiddle.net/wmrqk/4/
Try this:
function cleanCode() {
var container = $('<div>' + $('#text1').val() + '</div>');
container.find('img').removeAttr('onclick');
$('#text2').html(container.html());
}
Demo
May not be cool, but you can do something like
function cleanCode() {
var els = $($('#text1').val());
els.each(function(i, v){
var $this = $(this);
if($this.attr('id') == 'slideShowImage_1'){
$this.removeAttr('onclick')
}
});
console.log($('<div></div>').append(els).html())
}
Demo: Fiddle
For a very simple HTML like the one you have here you could do this :
$('#text2').html($('#text1').html().replace(/onclick="[^"]*"/g,''));
But be very careful : parsing HTML in regex fails in general cases so you can only do that if you know where your HTML comes from and what it is like.
If your HTML is well formed, you can also do this :
var e = $('<div>'+$('#text1').val()+'</div>');
e.find('img').attr('onclick','');
$('#text2').html(e.html());
Demonstration
In any case, be aware that this couldn't be used as a security measure.