最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

jquery - add class to span element with onClick javascript - Stack Overflow

matteradmin4PV0评论

I'm searching hours for an solution and found some answers, but not a quite fitting one.

I have several <span id="same-id-for-all-spans"></span> elements with each of them including one <img> element. Now I want to create a print template, to only print those elements which have a specific class added to it.

The question is, how can I add a class to a span by clicking on it. This way I want to "mark" several spans which then have an underlying print-css style to only print the ones with the specific*class*. Important: It should be possible to click (add class) and reclick (delete class) for single spans.

Thank you so much. Best Regards Mazey


its a wordpress return for all the spans, so same id. at the moment I have this js included:

<script type="text/javascript">
function changeid ()
{
var e = document.getElementById("nonprintable");
e.id = "printable";
}

</script>

and the wordpress code looks like this:

<?php
        $args = array('post_type' => 'attachment', 'post_parent' => $post->ID,  'orderby' => 'menu_order', 'order' => 'ASC'); 
                $attachments = get_children($args); 
foreach ( $attachments as $attachment_id => $attachment ) {


echo '<span id="nonprintable"  onClick="changeid()" >';
           echo wp_get_attachment_image( $attachment->ID, 'large' );

      echo '</span>';

          }


?>  

Right now when I click on a span I see that it changes the id. But it changes it just top to bottom with every click on a span and not on a specific span I click.

I'm searching hours for an solution and found some answers, but not a quite fitting one.

I have several <span id="same-id-for-all-spans"></span> elements with each of them including one <img> element. Now I want to create a print template, to only print those elements which have a specific class added to it.

The question is, how can I add a class to a span by clicking on it. This way I want to "mark" several spans which then have an underlying print-css style to only print the ones with the specific*class*. Important: It should be possible to click (add class) and reclick (delete class) for single spans.

Thank you so much. Best Regards Mazey


its a wordpress return for all the spans, so same id. at the moment I have this js included:

<script type="text/javascript">
function changeid ()
{
var e = document.getElementById("nonprintable");
e.id = "printable";
}

</script>

and the wordpress code looks like this:

<?php
        $args = array('post_type' => 'attachment', 'post_parent' => $post->ID,  'orderby' => 'menu_order', 'order' => 'ASC'); 
                $attachments = get_children($args); 
foreach ( $attachments as $attachment_id => $attachment ) {


echo '<span id="nonprintable"  onClick="changeid()" >';
           echo wp_get_attachment_image( $attachment->ID, 'large' );

      echo '</span>';

          }


?>  

Right now when I click on a span I see that it changes the id. But it changes it just top to bottom with every click on a span and not on a specific span I click.

Share edited Jun 27, 2013 at 13:03 Mazey asked Jun 27, 2013 at 12:56 MazeyMazey 371 gold badge2 silver badges9 bronze badges 5
  • 1 can you show your code ? – Raptor Commented Jun 27, 2013 at 12:57
  • 3 any reason you have got same id for all spans? – manraj82 Commented Jun 27, 2013 at 12:59
  • can you not edit he PHP code where it assigns a unique ID to the span? Are you thinking of setting IDs after the page has been rendered? I dont think thats a good idea whatever it is you are trying to achieve – manraj82 Commented Jun 27, 2013 at 13:12
  • like explained above, I want to add classes to the spans afterwards, so that in the print template the class-name decides which image is displayed, and which ones are not. If u have any other suggestion, I'm happy :) – Mazey Commented Jun 27, 2013 at 13:22
  • I think I dont need the "id". The "class" I only need for the print template. Instead of the "id" I only want to change the style of the span. So when I click one, I want it to have a border. Can someone help me with that? – Mazey Commented Jun 27, 2013 at 13:33
Add a ment  | 

6 Answers 6

Reset to default 5

you can use

jQuery('span').click(function(){
  jQuery(this).toggleClass('yourSpecialClass');
});

First of all, you should not have the same id for all your spans. Instead add a class to all of them like this:

<span class="selectable"></span>

Then you can do this:

$(function(){
  $(".selectable").click(function(){
     $(this).toggleClass("selected");
  });
});

And then in your function

function getAllSelected(){
   var selected = $(".selected"); // This will give you all the selected elements.
}

could use the following

$("span").click(function() {
   if($(this).hasClass("classname"))
   {
      $(this).removeClass("classname");
   }
   else
   {
      $(this).addClass("classname");
   }

});

Add an onclick handler and toggle CSS classes:

JS:

function addClass(obj) {
    obj.className ? obj.className = "" : obj.className = "test";
}

CSS:

.test {
    color: red;
}

HTML Span:

<span onclick="addClass(this)">Click me!</span>

Demo: http://jsfiddle/yXWcW/1/

Edit: Didn't see the jQuery tag, use toggleClass for that.

    <div class="items">
        <span class="item">Click Item 1</span>    
        <span class="item">Click Item 2</span>  
        <span class="item">Click Item 3</span>  
    </div>

   <div class="btn-getSelectedItems">Get Selected Items</div>

   $(function(){
        $('.items .item').click(function(){
            $(this).toggleClass('selected');
        })

       $('.btn-getSelectedItems').click(function(){
         if($('.items .selected').length){
            console.log($('.items .selected'))
         }
       })
    })

You can do this

<span id="nonprintable"  onClick="changeid(this)" >

added "this" to arguments

and your function would be

<script type="text/javascript">
function changeid (e){//added e to accepted arguments
    e.id = "printable";
    //e is the element so you are only changing that one elements id
}
</script>

or you can just use jQuery's .toggleClass

<span onclick="$(this).toggleClass('your-classname');">Click me!</span>

Since you have multiple instances (I would reend classes instead of id's)

$('#same-id-for-all-spans').click(function(){

    $(this).toggleClass('your-classname');

});

Here is the jQuery doc for .toggleClass()

http://api.jquery./toggleClass/

Post a comment

comment list (0)

  1. No comments so far