3

I have got a div containing some html elements. They all have a class named

class="fileItem read write".

But there could be an Element with

class="fileItem read write selected".

Now I want to get this element with the additional 'selected' tag and edit this. Currently I have an in JQuery

$(".fileItem").click(function(){
    // Code
});

which detect an click on one of these fileItems.

Here I want to edit style tag of the element with 'selected' tag. So is there something where I can say get all by class and select the on with "selected"?

2
  • you need to use hasClass Commented Jul 4, 2017 at 11:14
  • why not use $(".fileItem.selected") - This will only be called when classselected is present with class fileItem. Commented Jul 4, 2017 at 11:16

7 Answers 7

5

Just chain the desired class names like you would do in a CSS selector:

$(".fileItem.selected").click(function() {
    // do stuff
});'
Sign up to request clarification or add additional context in comments.

Comments

1
$(".fileItem").click(function(){
      $(this).find('.selected').style('blah','blah')
});

Something like this will allow you to perform other functions as well as the selected item.

Comments

1

$(".fileItem").click(function(e) {
  e.preventDefault();
  
  $('.selected').css({
    'color': 'green'
  });
});

Comments

0

You can simply use this line of code to get the element with the selected class

$(".fileItem.read.write.selected").click(function() {
    // code here
});'

Comments

0

You can use

   $(".selected").click(function(){});

5 Comments

Unsafe solution - having some other objects with .selected class in DOM we'll affect them.
If we think it this way then anything in DOM can get affected with any selector :)
Yes, but .selected isn't a name precisely describing nature of the object while .fileItem seems to be. There's high probability that some other objects will be .selected too.
Ok, for small projects that doesn't matter, but I think that's just bad practice. Safer solution could be naming the class .fileItemSelected, but that's overkill having ability of chaining classes in selectors (.fileItem.selected).
You can also put html body div#id.class > .fileItem.selected. The more minimalistic the better.
0

Use core java script to do this.

function func() {
alert("Hello, world!");
}

document.getElementsByClassName("fileItem read write selected")
[0].addEventListener("click", func, false);

Comments

0

As far as I know you should be able to combine the two classnames:

$(".fileItem.selected").click(function() {
//your actions
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.