Basically, I have to change a part of the page using jquery, but given the format of the page, I'm extremely confused as to what the chain of selectors has to be.
<span class="foo1">
<span class="intro"><span class="bar">data I need to change</span></1>
<span>...</span>
<div class="body">This is the only place I can write code on the page</div>
</span>
How can I change the data I need to change in using jquery? I don't have server access, obviously.
The code MUST start with $(this), because that 1 in foo is always a random number, and I can't guess it. The code must work for all posts, based on the post the code is in.
If I could use normal nesting, I would.The code must look something like
$(this).sibling('.intro').child('.bar').text('bar');
WORKING FIDDLE--CHAIN of Selectors
For nesting purpose,this is how you select:
$('.foo1 > .intro > .bar').text("text to be changed");
The above code indicates that bar is inside intro and intro is inside foo1.
Incase,if you still have doubts,Refer this->Nested selectors
As others have suggested,
$('.foo1 .intro .bar').html("text to be changed");
this is also a perfect way to approach nesting.
Well from the small snippet of markup you've given, you can do it like this:
$(".bar").text("Whatever you want it to say instead");
But if there are other elements that match .bar you will need to be more specific:
// All of these would select that element
$(".intro .bar")
$(".foo1 .intro .bar")
$(".intro > .bar")
$(".intro:first-child .bar")
If you need to select it relative to the .body element:
// All of these would work
$(".body").siblings(".intro").find(".bar")
$(".body").parent().find(".bar")
I think you get the point... we can't give you a proper answer unless you expand your question.
If I understand the question.
You can only add code in <div class="body">. But you want change the text inside .bar
<span class="foo1">
<span class="intro"><span class="bar">data I need to change</span></span>
<span>...</span>
<div class="body">
This is the only place I can write code on the page
<script type="text/javascript">
$('.foo1 .intro .bar').html('Changed!');
</script>
</div>
</span>
You could do also simply $('.bar').html('Changed') but if you have multiple span.bar that's more safe.
http://jsfiddle.net/u4djZ/1
$('.foo1>.intro>.bar').text('Data Changed!');
As MESSIAH pointed out, you should use the CSS child selector.
here:
<span class="foo1">
<span class="intro"><span class="bar">data I need to change</span></1>
<span>...</span>
<div class="body">
<script>
$(document).ready(function() { // you need this to make sure document is loaded
$('.foo1 .intro .bar').html("new text");
});
</script>
</div>
</span>
you need to wrap your js code in
$(document).ready(function() { /* your code here */ });
or - if jquery library is loaded at the bottom of the page:
window.onload = function () { /* your code here */ };
to make sure jquery and DOM elements are in place before you try to access them.
You can use -
$(document).ready(function() {
$('.foo1 .intro .bar').html("new text");
});
Referance
the correct answer for my question ended up being
<script class="12345">
$('.12345').parents('.foo').find('.intro>.bar').text('whatever');
</script>
thanks for all your help :)
Related
Hopefully I can explain my question correctly, so sorry in advance for any wrong use of jargon or other:
Is it possible to access with javascript the original markup as viewed in the source code rather then the code from the DOM after it has been 'modified'
Let's say an element #div1 has the actual text that will be used in another element with id #div2, in the source code the text will be visible in #div1 but in the DOM while inspecting #div1 will be empty and #div2 will have that text,
I know it would be a matter of the order of loading the scripts, but I was hoping there could be another way.
Hopefully this makes some sense.
Yep, the simpliest way to access original html is to place your js code before any other scripts (or place only libs like jquery before).
The second opportunity is to load document again with ajax, parse and get what you want. Here is code example:
<div id="div1">
Hello
</div>
<div id="div2">
</div>
<script type="text/javascript" src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script>
$('#div2').html($('#div1').html())
$('#div1').html('')
</script>
<script>
alert($('#div1').html())
// ajax get
// empty string in get request means current location
$.get("", function (html) {
var el = $(html).filter('#div1');
alert(el.html())
});
</script>
How to add text from span tag to data-attr?
Example:
I have this code
<div class="clearfix colelem" id="u92-5"><!-- content -->
<p>Icon<span id="u92-2">iconsymbol</span></p>
</div>
And I want to add iconsymbol to data-attr="iconsymbol" of the same element like a:
<div class="clearfix colelem" id="u92-5" data-attr="iconsymbol"><!-- content -->
<p>Icon<span id="u92-2">iconsymbol</span></p>
</div>
Yes and it will be with all elements which has a title="icon"
<script>
$( document ).ready(function() {
$("[title*='icon']").attr('data-attr',function(){
// I don't know
}).removeAttr('title');
});
</script>
Do you know how to do it?
So I know it is very simple but I am new in jquery and I need in your help.
I hope you understood my question.
Here is an example that should work for you. There is probably a few ways you can pull this off, but this should hopefully get you started. Please see the attached JSFiddle to see this example in action
$(function() {
$('[title*="icon"] span').each(function(){
$(this).parent().closest('div').attr('data-attr', $(this).text())
});
});
Here is another way you can do this as well
$('[title*="icon"]').each(function(){
$(this).attr('data-attr', $(this).children().closest('span').text());
});
JSFiddle Example
Your <div>s should have attribute title="icon"
You are using a callback to attr() function, so return the value which you need to set inside the function using .text().
$(document).ready(function () {
$("[title='icon']").attr('data-attr', function () {
return $(this).find('span').text();
}).removeAttr('title');
});
Demo
just having some issues with this jQuery thing.
What i'm trying to do is:
i have some audio control buttons that look like this:
<p>Play audio</p>
but there are too many on the page so i'm trying to optimise the code and make a little function that checks for the div id on the button and adds tells the player what track to play.
so i've done this:
<div id="audioControlButtons-1">
<div class="speaker"> </div>
<div class="play"> </div>
<div class="pause"> </div>
</div>
<script>
$(document).ready(function() {
$("[id^=audioControlButtons-] div.play").click(function() {
var id = new Number;
id = $(this).parent().attr('id').replace(/audioControlButtons-/, '');
//alert(id);
player1.loadAudio(id);
return false;
});
});
</script>
my problem is:
the id is not passing to the the player1.loadAudio(id)
if i hardcode player1.loadAudio(1)
it works! but the moment i try to pass the variable to the function it doesn't work...
however if you uncomment the alert(id) thing you will see the id is getting generated...
can someone help?
cheers,
dan
I think I see your problem. The variable id is a string. Try;
player1.loadAudio(parseInt(id));
Yah and the initialise line isn't necessary. Just use;
var id = $(this).parent().attr('id').replace(/audioControlButtons-/, '');
I'm actually kind of confused with your example because you originally have this:
<p>Play audio</p>
but then you don't reference it again. Do you mean that this html:
<div id="audioControlButtons-1">
<div class="speaker"> </div>
<div class="play"> </div>
<div class="pause"> </div>
</div>
Is what you are actually creating? If so, then you can rewrite it like this:
<div class="audio-player">
<div class="speaker"> </div>
<div class="play" data-track="1"> </div>
<div class="pause"> </div>
</div>
Then in your script block:
<script>
$(document).ready(function() {
$(".audio-player > .play").click(function() {
var track = $(this).data('track');
player1.loadAudio(+track);
return false;
});
});
</script>
So a few things are going on here.
I just gave your containing div a class (.audio-player) so that it's much more generic and faster to parse. You don't want to do stuff like [id^=audioControlButtons-] because it is much slower for the javascript to traverse and parse the DOM like that. And if you are going to have multiples of the same element on the page, a class is much more suited for that over IDs.
I added the track number you want to the play button as a data attribute (data-track). Using a data attribute allows you to store arbitrary data on DOM elements you're interested on (ie. .play button here). Then this way, you don't need to this weird DOM traversal with a replace method just to get the track number. This saves on reducing unnecessary JS processing and DOM traversing.
With this in mind now, I use jQuery's .data() method on the current DOM element with "track" as the argument. This will then get the data-track attribute value.
With the new track number, I pass that along into your player1.loadAudio method with a + sign in front. This is a little javascript trick that allows you to convert your value into an actual number if that is what the method requires.
There are at least a couple of other optimizations you can do here - event delegation, not doing everything inside the ready event - but that is beyond the scope of this question. Hell, even my implementation could be a little bit optimized, but again, that would require a little bit more in depth explanation.
Question: So let's say I have some basic code
<a name = "sec">this is a test</a>
I want a javascript function to on click of a link to change that to
So user clicks:
link!
And the JS kicks in to change the 1st html to:
<font color = "green"><a name = "sec">this is a test</a></font>
Is it possible to do this in JS?
You can set the element's color with JS as a simple solution. You should also give the element a valid href attribute that nullifies the default click behavior.
<a name="sec" href="javascript:void(0);" onclick="this.style.color='green';">
this is a test
</a>
Try something along the lines of
link
And you should not use <font> tag for setting text attributes, this is considered bad practice in today’s HTML (be it XHTML or HTML5).
Something like this should work: (Psudeo Code)
<a id="sec" onClick="makeGreen()">this is a test</a>
<script type="text/javascript" charset="utf-8">
function makeGreen() {
document.getElementById('sec').style.color('green');
};
</script>
Realistically, you should keep your semantics and your style separate. As other users have suggested, use a css class instead of modifying styles directly. This is fairly easy to do, as shown by this jsFiddle
This is a test
<script type="text/javascript">
var el = document.getElementById('my-link');
el.addEventListener('click', function() {
this.className = 'clicked-class';
});
</script>
And of course in your CSS you would define some sort of rule:
.clicked-class {
color: green;
}
This could be made even simpler with a javascript library of your choice, but hopefully should be enough to get you started.
$(element).on("click",function() {$(this).css({'color', 'blue'});
Is it possible to copy javascript with javascript? For example:
<div class="copyThis">
<script language="javascript">
$(function()
{
$("#click").click(function(e){
$('.copyThis').clone().appendTo('#copyArea');
e.preventDefault();
});
});
</script>
CONTENT CONTENT CONTENT CONTENT CONTENT CONTENT CONTENT CONTENT CONTENT
<div style="width: 200px; height: 50px; background-color: gray;">
<a id="click" href="">click here to copy</a>
</div>
<div id="copyArea">
Put here:
</div>
</div>
But this doesn't copy the tag and its content. At least, not that I know of.
NOTE:
I came upon this question in relationship to a different question I had posted here: Infinite-loop question: Is it possible to make a "Copy this code to share", with a "copy this code to share" inside of it?
I hope it's ok to post this question separately as it's sort of a curiosity thing.
EDIT: I think this is what you want. This (demo) will fill a textarea for easy copying:
<div id="copyThis">
<script language="javascript">
$(function()
{
$("#click").click(function(e){
$('#copyArea').val($('#copyThis').html());
e.preventDefault();
});
});
</script>
CONTENT CONTENT CONTENT CONTENT CONTENT CONTENT CONTENT CONTENT CONTENT
<div style="width: 200px; height: 50px; background-color: gray;">
<a id="click" href="">click here to copy</a>
</div>
<textarea rows="10" cols="40" id="copyArea"></textarea>
</div>
You were doing DOM manipulation before ready. Use:
<script language="javascript">
$(function()
{
$("#click").click(function(e){
$('#copyThis').clone().appendTo('#copyArea');
e.preventDefault();
});
});
</script>
See the demo.
I think in a round about way what your trying to do is covered by jquery's live methods.
<div class="copy">
<a class="click-me">click me</click>
</div>
<script type="text/javascript">
$('.click-me').live('click',function(e){
$(e).parent().clone().appendTo('#copyArea');
})
</script>
Using Live will re-bind the new element to the click handler without having to copy a javascript block
If you want the click event to be cloned also, you need to set the withDataAndEvents argument to true in clone
$('.copyThis').clone(true).appendTo('#copyArea');
Note: this answer is to a question different from the one actually asked :-) I'll leave it here as a historical curiosity however.
The problem is very likely to be that your <script> tags are just not being executed. If what you want to happen is that your cloned <div> have the same "click" handler, however, you should really go about it in a totally different way:
Use a "class" instead of an "id" to mark the <div> elements that should be affected; say, "cloneMe"
Use the jQuery .live() or (better) .delegate() facilities to set up the handler so that it operates off of bubbled events, and can therefore handle clicks on cloned <div> blocks.
(then in your Javascript somewhere: )
$(function() {
$('body').delegate("div.cloneMe", "click", function(ev) {
$(this).clone().appendTo('#copyArea');
ev.preventDefault();
});
});
Now you should be able to clone to your heart's content, and you don't have to worry about that bad old Javascript jammed so obtrusively into your code.
edit — ah - I now see that I was completely confused about what it was that was getting clicked. If the clicking is happening on a separate button (or <a> or whatever), then there's really no need to have the script stuck in the middle of the page at all; the whole thing should just be a simple event handler setup.