最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - If element has class - Stack Overflow

programmeradmin1浏览0评论

I am trying to translate a field error by testing if a an element have the class sv or en (swedish or english)

I tried to access the class but won't affect the javascript oute.


input.oninvalid = function(event) {
  if ($("wgcurrent").hasClass("en")) { 
    event.target.setCustomValidity("Letters only please");  
  } else if ($("wgcurrent").hasClass("sv")) {
    event.target.setCustomValidity("Vänligen ange endast bokstäver");
  }  

}
<div class="wgcurrent wg-li wg-flags  flag-1 en" data-l="en" tabindex="0" aria-expanded="false" role="bobox" aria-label="Language selection: English"><a tabindex="-1" href="javascript:%20void(0);">English</a></div>

I want to make sure the input function sets the right value for the error message. What do I need to change?

I am trying to translate a field error by testing if a an element have the class sv or en (swedish or english)

I tried to access the class but won't affect the javascript oute.


input.oninvalid = function(event) {
  if ($("wgcurrent").hasClass("en")) { 
    event.target.setCustomValidity("Letters only please");  
  } else if ($("wgcurrent").hasClass("sv")) {
    event.target.setCustomValidity("Vänligen ange endast bokstäver");
  }  

}
<div class="wgcurrent wg-li wg-flags  flag-1 en" data-l="en" tabindex="0" aria-expanded="false" role="bobox" aria-label="Language selection: English"><a tabindex="-1" href="javascript:%20void(0);">English</a></div>

I want to make sure the input function sets the right value for the error message. What do I need to change?

Share Improve this question edited Aug 13, 2019 at 17:30 Luvexina 84311 silver badges26 bronze badges asked Aug 13, 2019 at 17:28 9minday9minday 4034 gold badges10 silver badges22 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 6

As noted in the jquery docs: https://api.jquery./class-selector/

The selector for objects with a class is not

$("wgcurrent")

It's like this:

$(".wgcurrent")

The dot makes it so it selects any object with the wgcurrent class.

I believe that's the reason behind your issue, since the hasClass should work in this scenario.

However beware that this will select ALL the objects with the wgcurrent class.

Pure JavaScript look at classList

console.log(element.classList.contains('en'));//output true 

发布评论

评论列表(0)

  1. 暂无评论